繁体   English   中英

C#中的通用方法

[英]Generic Methods in C#

一般来说,通用方法对我来说都是新的。 需要一个返回泛型类型的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)'的类型参数。 尝试显式指定类型参数。

反正有没有这样做?

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

你传入了一个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());
}

我建议你阅读msdn上的Expressions

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

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

如果要返回Collection,可能需要调用ToList()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM