简体   繁体   中英

IQueryable<T> cast to IList<SpecificInterface>

Setup

public interface ITable { }

public class Company : ITable {
    public int Id { get; set; }
    public string Name { get; set; }
}

public class PaginationGridModel {

    public PaginationGridModel(IList<ITable> rows) {
        //cool stuff goes here
    }
}

public GridModel GenerateModel<T>(IQueryable<T> Table) where T : ITable {
    return new GridModel((IList<ITable>)Table);
}

//Actual Call
return GenerateModel<Company>(this.dataContext.Companies);

Exception Generated

Unable to cast object of type 'System.Collections.Generic.List`1[Company]' to type 'System.Collections.Generic.IList`1[ITable]'.

Question

Since Company implements ITable I should be able to convert my List<Company> into an IList<ITable> however it doesn't want to work because it's actually T . But T is constrained in the function definition to an ITable . What am I doing wrong here? When I'm not using Generics the setup works just fine. However I wanted a Generic setup because I've been writing the same code over and over - which is bad :)

Any help would be greatly appreciated. Even if what you tell me is that it can't be done.

对于.NET 3.5,您可以使用:

return new GridModel(table.ToList().ConvertAll(x => (ITable)x));

如果这是.NET 4.0,您可以阅读有关通用协方差和逆变的信息

You can also use the LINQ Cast() extension method:

return new GridModel((IList<ITable>)Table.Cast<T>());

which is a bit clearer.

Also it is often nicer to use IEnumerable instead of IList when possible.

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