protected void Page_Load(object sender, EventArgs e)
        {            int[] arr1 ={ 1,2,3,4,5,6};
            int[] arr2 =  { 1,2,3,4};
            int[] arr3 =  { 1,2,3,4};
            int[] arr4 =  { 1,2,3,4,5,6,7};
            int[] arr5 =  { 1,2,3,4,5,6,7,8};
            
            List<int[]> arr = new List<int[]> { arr1,arr2,arr3,arr4,arr5};            arr.Sort(
                delegate(int[] x,int[] y) {
                    return
                        x.Length > y.Length ? -1 :
                        x.Length < y.Length ? 1 :
                        0;
                }
                );
            this.GridView1.DataSource = arr;
            this.GridView1.DataBind();
        }
请问上面这段代码,Sort方法里使用委托有什么作用?它的运行过程是怎样的?这样做有什么好处?谢谢!

解决方案 »

  1.   

    看这个帖子
    http://topic.csdn.net/u/20090805/16/1c97b67f-9767-4ebf-a074-20aeb16a665a.html?43004

    大笨狼的回复
      

  2.   


    很遗憾,那个帖子中3楼的回复是错误的。这个写法是匹配 public void List<T>.Sort(Comparison<T> comparison) 定义的,而没有根据张冠李戴到public void List<T>.Sort(IComparer<T> comparer)。
      

  3.   

    前者中参数的类型定义是这样的public delegate int Comparison<T>(T x, T y);
    可见这个定义明显地定义了delegate的语法格式。把它不小心跟IComparer<T>接口搞错了并不稀奇,但是后边那么多人都没有感觉到要刨根问底一下?
      

  4.   

    我们再来看.net如何实现的:public void Sort(Comparison<T> comparison)
    {
        if (comparison == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
        }
        if (this._size > 0)
        {
            IComparer<T> comparer = new Array.FunctorComparer<T>(comparison);
            Array.Sort<T>(this._items, 0, this._size, comparer);
        }
    }
    它需要另外制造一个ICompare<T>(的具体类)对象然后才使用那个关于接口的方法。
      

  5.   

    这么做的好处就是排序本来就不用你管,如果你要管排序你就实现ICompare <T>接口,
    如果你不管排序你就把怎么排告诉.net,如按升序还是降序等,这就是这个委托的意义
      

  6.   

    呵呵,看那个帖子是被首页推荐的标题“算法必须知道的基本知识复杂度模型”给吸引进去的,还真没看那些代码...不如sp1234认真啊...如sp1234所述,这里的委托是和IComparer<T>接口没有直接关系,委托只关心签名...