繁体   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