简体   繁体   中英

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). I would strongly prefer to do this in the constructor if at all possible.

This is my 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

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.

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. I want to supply defaults via overloaded constructors. How would I go about doing this?

a => a.Time

Time is a DateTime . TOrderBy might not be a DateTime , for example:

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

So, you can't do what you're trying to do.


That TOrderBy is a big pain! The best idea would be to avoid the problem by not having a TOrderBy as part of the class if you can help it. This answer shows a way to wrap the ordering expression to hide the TOrderBy from the outside world.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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