這可能是一個相對簡單的監督,但是我無法弄清楚,如果我真的被允許這麼做,或者可能是一個合理的替代方案(在VS2010中使用,C#.Net 4.0)。如果可能的話,我強烈希望在構造函數中這樣做。在構造函數中的表達式<Func <MyType,TOrderBy >>中使用泛型
這是我的課:
public class MyClass1<TOrderBy> : MyInterface1<MyType1, MyType2>
{
public MyClass1(IEnumerable<Guid> ids) : this(ids, 0, 10, a => a.Time, ListSortDirection.Ascending) { }
public MyClass1(IEnumerable<Guid> ids, int pageIndex, int itemsPerPage, Expression<Func<MyType2, TOrderBy>> orderBy, ListSortDirection sortDirection)
{
this.pageIndex = pageIndex;
this.itemsPerPage = itemsPerPage;
this.orderBy = orderBy;
this.sortDirection = sortDirection;
this.ids = ids != null ? ids.ToList() : new List<Guid>();
}
}
徘徊時超過a => a.Time
和錯誤Cannot convert lambda expression to delegate type 'System.Func<MyType2,TOrderBy>' because some of the return types in the block are not implicitly convertible to the delegate return type
和Cannot implicitly convert type 'System.DateTime' to 'TOrderBy'
建設時,我得到的錯誤
Cannot convert expression type 'System.DateTime' to return type 'TOrderBy'
。如你可能工作,我想建立一個類,在構造函數中的信息排序和頁面IQueryable。 我想通過重載的構造函數提供默認值。我會如何去做這件事?
'a'的類型是什麼? – Gabe 2012-04-05 15:15:18
'a.Time'應該有'TOrderBy'類型。不要在這裏欺騙編譯器。這是一個常見的問題/錯誤,在你的情況下是一個複雜的情況。 – leppie 2012-04-05 15:15:52
如果你確定'TOrderBy'總是一個'DateTime'(它本身就是其他的一些設計問題),你可以像'(TOrderBy)((object)value)一樣進行轉換。 – leppie 2012-04-05 15:20:15