2012-04-05 13 views
2

這可能是一個相對簡單的監督,但是我無法弄清楚,如果我真的被允許這麼做,或者可能是一個合理的替代方案(在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 typeCannot implicitly convert type 'System.DateTime' to 'TOrderBy'建設時,我得到的錯誤

Cannot convert expression type 'System.DateTime' to return type 'TOrderBy'。如你可能工作,我想建立一個類,在構造函數中的信息排序和頁面IQueryable。 我想通過重載的構造函數提供默認值。我會如何去做這件事?

+0

'a'的類型是什麼? – Gabe 2012-04-05 15:15:18

+0

'a.Time'應該有'TOrderBy'類型。不要在這裏欺騙編譯器。這是一個常見的問題/錯誤,在你的情況下是一個複雜的情況。 – leppie 2012-04-05 15:15:52

+0

如果你確定'TOrderBy'總是一個'DateTime'(它本身就是其他的一些設計問題),你可以像'(TOrderBy)((object)value)一樣進行轉換。 – leppie 2012-04-05 15:20:15

回答

0
a => a.Time 

時間是DateTimeTOrderBy可能不是一個DateTime,例如:

MyClass1<Car> x = new MyClass1<Car>(ids); 

所以,你不能做你想要做的事。


TOrderBy是一個很大的痛苦!最好的辦法是避免這個問題,因爲如果你可以幫助的話,不要把TOrderBy作爲課程的一部分。 This answer顯示了一種封裝排序表達式以隱藏來自外界的TOrderBy的方法。

+0

啊,謝謝,這有助於瞭解我要去哪裏錯誤與此... – cofiem 2012-04-05 15:51:24

+0

你鏈接到關於包裝順序表達式的答案看起來像要走的路。可以修改,以包括在Orderer '的構造函數中的順序(asc,desc)? – cofiem 2012-04-05 22:04:46

+0

@cofiem是的,它可以。重點是使用帶有一個類型參數的接口來引用具有兩個類型參數的類。 – 2012-04-05 22:12:36

相關問題