简体   繁体   English

在表达式中使用 generics <func<mytype, torderby> > 在构造函数中</func<mytype,>

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

This is probably a relatively simple oversight, but I can't work out if I'm actually allowed to do this, or what might be a reasonable alternative (using in VS2010, C#.Net 4.0).这可能是一个相对简单的疏忽,但我不知道我是否真的被允许这样做,或者什么可能是一个合理的替代方案(在 VS2010、C#.Net 4.0 中使用)。 I would strongly prefer to do this in the constructor if at all possible.如果可能的话,我强烈希望在构造函数中执行此操作。

This is my class:这是我的 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>();
        }
}

I get the error我得到错误

Cannot convert expression type 'System.DateTime' to return type 'TOrderBy' when hovering over a => a.Time悬停在a => a.Time上时Cannot convert expression type 'System.DateTime' to return type 'TOrderBy'

and the errors 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 and Cannot implicitly convert type 'System.DateTime' to 'TOrderBy' when building.和错误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'构建时。

As you can probably work out, I'm trying to build a class that takes information in the constructor to sort and page an IQueryable.正如您可能解决的那样,我正在尝试构建一个 class,它在构造函数中获取信息以对 IQueryable 进行排序和分页。 I want to supply defaults via overloaded constructors.我想通过重载的构造函数提供默认值。 How would I go about doing this?我将如何 go 这样做?

a => a.Time

Time is a DateTime .时间是DateTime TOrderBy might not be a DateTime , for example: TOrderBy可能不是DateTime ,例如:

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

So, you can't do what you're trying to do.所以,你不能做你想做的事。


That TOrderBy is a big pain! TOrderBy是一个很大的痛苦! The best idea would be to avoid the problem by not having a TOrderBy as part of the class if you can help it.如果可以的话,最好的办法是通过不将TOrderBy作为 class 的一部分来避免此问题。 This answer shows a way to wrap the ordering expression to hide the TOrderBy from the outside world.这个答案展示了一种包装排序表达式以对外界隐藏 TOrderBy 的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM