[英]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.