C#中使用委托对字符串进行冒泡排序案例

描述:把字符串比较方法委托给声明的委托类型变量,变量在传给冒泡排序方法,并返回结果,以下方式采用了不同的方法得到字符串的比较。
代码如下:
//声明委托
public delegate int BubblingSortHandler(string s1,string s2);

//控制台主程序

        /// 
        /// 冒泡排序
        /// 
        /// 
        /// 
        public static string[] BubblingSort(string[] lists,BubblingSortHandler handler)
        {
            for (int i = 0; i < lists.Length-1; i++)
            {
                for (int j = 0; j < lists.Length-1-i; j++)
                {
                    if (handler(lists[j],lists[j+1])>0)
                    {
                        string temp = lists[j];
                        lists[j] = lists[j + 1];
                        lists[j + 1] = temp;
                    }
                }
            }
            return lists;
        }



       //对字符串长度进行比较
        public static int HandlerByNumber(string s1, string s2)
        {
            return s1.Length - s2.Length;
        }
        //对字符串进行比较
        public static int HandlerByString(string s1, string s2)
        {
            return string.Compare(s1, s2);
        }



//主程序

static void Main(string[] args)
        {
            string[] strs = "金飞达,啊,凉皮机福建克雷格,让他坊四邻家里过节了可观,自然国瑞风,粉色减肥,风角色及家人".Split(',');
            //方法一:将字符串比较方法传给委托变量进行排序
            string[] result1 =  BubblingSort(strs, HandlerByNumber);//通过字符串长度比较得到的结果
            string[] result2 = BubblingSort(strs, HandlerByString);//通过字符串进行比较得到的结果
            //方法二:在声明委托变量,将字符串比较方法,给委托变量,然后在调用排序
            BubblingSortHandler handler1 = HandlerByNumber;
            BubblingSortHandler handler2 = HandlerByString;
            string[] result3 = BubblingSort(strs, handler1);
            string[] result4 = BubblingSort(strs, handler2);
            //方法三:匿名方法,不需要单独的方法对字符串进行比较
            BubblingSortHandler handlerSort1 = delegate(string s1, string s2)
            {
                return s1.Length - s2.Length;
            };
            string[] result5 = BubblingSort(strs, handlerSort1);
            string[] result6 = BubblingSort(strs, delegate(string s1, string s2)
            {
                return string.Compare(s1, s2);
            });
            //方法四:lambda方法,是对匿名方法的简化
            BubblingSortHandler handlerSort2=(s1,s2)=> s1.Length-s2.Length;
            string[] result7 = BubblingSort(strs, handlerSort2);
            string[] result8 = BubblingSort(strs, (s1, s2) => string.Compare(s1, s2));

            Console.WriteLine("最终所有result的结果全是以最后一次result8执行的结果,因为数组是引用类型!可以进行调试分析");
            Console.ReadKey();
        }

你可能感兴趣的:(C#面向对象范例,c#,委托,冒泡排序)