一般来说,泛型方法对我来说是新的。需要一个返回泛型类型集合的方法,但也需要一个相同泛型类型的集合并采用
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]);
}
但我收到错误:
Error: The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumberable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
有什么办法吗?
最佳答案
很抱歉回答了两次,但这确实是另一种解决方案。
您正在传递一个 Expression<Func<T, DateTime>>
但是 Orderby 想要一个 Func<T, DateTime>
您可以编译表达式:
return new Collection<T>(SortList.OrderBy(OrderByDateTime[0].Compile()).ToList());
或者直接传入函数作为参数:
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
关于c# - C# 中的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1471281/