C#中的通用方法

时间:2009-09-24 12:08:52

标签: c# generics collections methods generic-programming

通用方法一般来说对我来说都是新的。需要一个返回泛型类型的Collection的方法,但也需要一个相同泛型类型的集合并且需要

Expression<Func<GenericType, DateTime?>>[] Dates 

参数。整个以下函数的T应该是相同的类型,所以现在我正在使用(简化版):

private static Collection<T> SortCollection<T>(Collection<T> SortList, Expression<Func<T, DateTime>>[] OrderByDateTime)
{
    return SortList.OrderBy(OrderByDateTime[0]);
}

但我收到错误:

  

错误:方法的类型参数   “System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumberable,   System.Func)'不能   从用法推断。尝试   指定类型参数   明确。

有没有这样做?

2 个答案:

答案 0 :(得分:6)

很抱歉回答两次,但这是合法的另一种解决方案。

你传递的是Expression<Func<T, DateTime>>,但是Orderby需要Func<T, DateTime>

您可以编译表达式:

return new Collection<T>(SortList.OrderBy(OrderByDateTime[0].Compile()).ToList());

或直接输出funcs作为参数:

private static Collection<T> SortCollection<T>(Collection<T> SortList, Func<T, DateTime>[] OrderByDateTime)
{
    return new Collection<T>(SortList.OrderBy(OrderByDateTime[0]).ToList());
}

我建议您阅读Expressions on msdn

答案 1 :(得分:4)

在这种情况下,编译器无法确定您打算向OrderBy方法提供哪些类型参数,因此您必须明确提供它们:

SortList.OrderBy<T, DateTime>(OrderByDateTime[0])

如果您想要返回收藏品,您可能想要致电ToList()

相关问题