[英]IQueryable<T> cast to IList<SpecificInterface>
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);
Unable to cast object of type 'System.Collections.Generic.List`1[Company]' to type 'System.Collections.Generic.IList`1[ITable]'.
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
. 由于
Company
实施ITable
我应该能够将我的List<Company>
转换为IList<ITable>
但是它不想工作,因为它实际上是T
But T
is constrained in the function definition to an ITable
. 但是
T
在函数定义中受限于ITable
。 What am I doing wrong here? 我在这做错了什么? When I'm not using Generics the setup works just fine.
当我不使用Generics时,设置工作正常。 However I wanted a Generic setup because I've been writing the same code over and over - which is bad :)
但是我想要一个Generic设置,因为我一直在编写相同的代码 - 这很糟糕:)
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: 您还可以使用LINQ Cast()扩展方法:
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. 此外,在可能的情况下使用IEnumerable而不是IList通常更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.