Generic method

public class SortableObservableCollection<T> : ObservableCollection<T>
    {
        public void Sort<TR>(Func<T, TR> resultSelector, ListSortDirection direction)
        {
            switch (direction)
            {
                    case ListSortDirection.Ascending:
                    ApplySort(Items.OrderBy(resultSelector));
                    break;
                    case ListSortDirection.Descending:
                    ApplySort(Items.OrderBy(resultSelector));
                    break;
            }
        }

        public void Sort<TR>(Func<T, TR> resultSelector, IComparer<TR> comparer)
        {
            this.ApplySort(Items.OrderBy(resultSelector,comparer));
        }
        private void ApplySort(IEnumerable<T> orderBy)
        {
            var sortedItemlist = orderBy.ToList();
            foreach (var item in sortedItemlist)
            {
                this.Move(this.IndexOf(item),sortedItemlist.IndexOf(item));
            }
        }
    }

  

泛型的使用:

sortableObservable.Sort(info => new ProcessInfo(),ListSortDirection.Ascending);

为什么sort不用写参数呢?

可以看到我的编译器是识别,参数的

You can also omit the type argument and the compiler will infer it. The following call to Swap is equivalent to the previous call

static void Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
}
可以这么使用
int a = 1;
    int b = 2;

    Swap<int>(ref a, ref b);
或者这样子
Swap(ref a, ref b);

The same rules for type inference apply to static methods and instance methods. The compiler can infer the type parameters based on the method arguments you pass in; it cannot infer the type parameters only from a constraint or return value. Therefore type inference does not work with methods that have no parameters. Type inference occurs at compile time before the compiler tries to resolve overloaded method signatures. The compiler applies type inference logic to all generic methods that share the same name. In the overload resolution step, the compiler includes only those generic methods on which type inference succeeded.

Within a generic class, non-generic methods can access the class-level type parameters, as follows:

class SampleClass<T>
{
    void Swap(ref T lhs, ref T rhs) { }
}

如果我删除Sort<TR> 就会报错:


posted @ 2014-05-27 16:03  penney  阅读(190)  评论(0)    收藏  举报