C#中的通用方法

Ste*_*eph 2 c# generics collections methods generic-programming

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

Expression<Func<GenericType, DateTime?>>[] Dates 
Run Code Online (Sandbox Code Playgroud)

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

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

但我收到错误:

错误:无法从用法推断出方法'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumberable,System.Func)'的类型参数.尝试显式指定类型参数.

反正有没有这样做?

Rob*_*sor 6

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

你传了一个Expression<Func<T, DateTime>>但是Orderby想要一个Func<T, DateTime>

您可以编译表达式:

return new Collection<T>(SortList.OrderBy(OrderByDateTime[0].Compile()).ToList());
Run Code Online (Sandbox Code Playgroud)

或直接输出funcs作为参数:

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

我建议你阅读msdn上的Expressions