c# - C# 中的泛型方法

标签 c# generics collections methods generic-programming

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

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/

相关文章:

swift - Swift 中的泛型变量声明

java - 将链接的对象变成流或集合

java - "new List()"符号是什么意思?

c# - PayPal API,找到合适的

c# - 使用 Google Drive Api v2 选择特定字段

java - 概念证明 : how I can create a generic comparator method with reflection?

java - 类数组列表的迭代器

C# 将泛型列表复制到具有较少列的对象

c# - 有 2 组数据的自连接表的条件 LINQ 查询

java - 不能将 A[T] 隐式转换为 AT,其中 A[T] 扩展 AT