一般来说,通用方法对我来说是新的。需要一个方法,该方法返回泛型类型的集合,但也接受相同泛型类型的集合并接受
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)' 不能
从使用情况推断。尝试
指定类型参数
明确地。
有办法做到这一点吗?
Generic Methods in general are new to me. Need a method that returns a Collection of a generic type, but also takes a collection of the same generic type and takes
Expression<Func<GenericType, DateTime?>>[] Dates
parameter. T throughout the following function should be the same type, so right now I was using (simplified version):
private static Collection<T> SortCollection<T>(Collection<T> SortList, Expression<Func<T, DateTime>>[] OrderByDateTime)
{
return SortList.OrderBy(OrderByDateTime[0]);
}
but i'm receiving error:
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.
Is there anyway to do this?
发布评论
评论(2)
抱歉回答两次,但这实际上是另一个解决方案。
您传入的是
Expression>
,但 Orderby 想要Func
您可以编译表达式:
或传入直接将 funcs 作为参数:
我建议阅读 Expressions on msdn
Sorry for answering twice, but this is legitimately another solution.
You're passing in an
Expression<Func<T, DateTime>>
but Orderby wants aFunc<T, DateTime>
You can either compile the expression:
or pass in straight out funcs as arguments:
I'd recommend reading up on Expressions on msdn
在这种情况下,编译器无法确定您打算向 OrderBy 方法提供什么类型参数,因此您必须显式提供它们:
您可能需要调用
ToList()
如果你想要返回一个集合In this situation, the compiler is failing to figure out what type arguments you intend to provide to the OrderBy method, so you'll have to supply them explicitly:
You'll probably want to call
ToList()
if you want a Collection to be returned