簡體   English   中英

在表達式中使用 generics <func<mytype, torderby> > 在構造函數中</func<mytype,>

[英]Using generics in an Expression<Func<MyType, TOrderBy>> in a Constructor

這可能是一個相對簡單的疏忽,但我不知道我是否真的被允許這樣做,或者什么可能是一個合理的替代方案(在 VS2010、C#.Net 4.0 中使用)。 如果可能的話,我強烈希望在構造函數中執行此操作。

這是我的 class:

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 expression type 'System.DateTime' to return type 'TOrderBy'

和錯誤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'構建時。

正如您可能解決的那樣,我正在嘗試構建一個 class,它在構造函數中獲取信息以對 IQueryable 進行排序和分頁。 我想通過重載的構造函數提供默認值。 我將如何 go 這樣做?

a => a.Time

時間是DateTime TOrderBy可能不是DateTime ,例如:

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

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


TOrderBy是一個很大的痛苦! 如果可以的話,最好的辦法是通過不將TOrderBy作為 class 的一部分來避免此問題。 這個答案展示了一種包裝排序表達式以對外界隱藏 TOrderBy 的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM