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
. W开发者_如何学JAVAhat 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.
For .NET 3.5 you can use this:
return new GridModel(table.ToList().ConvertAll(x => (ITable)x));
If this is .NET 4.0 you could read about generic covariance and contravariance.
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.
精彩评论