IQueryable转换为 IList;
设置
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]'.
问题
由于 Company
实现了 ITable
我应该能够将我的 List
转换为 IList
T
。但 T
在函数定义中被限制为 ITable
。我在这里做错了什么?当我不使用泛型时,设置工作得很好。不过,我想要一个通用设置,因为我一直在一遍又一遍地编写相同的代码 - 这很糟糕:)
任何帮助将不胜感激。即使你告诉我这是不可能的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于.NET 3.5,你可以使用这个:
For .NET 3.5 you can use this:
如果这是 .NET 4.0,您可以阅读有关通用协变和逆变的内容。
If this is .NET 4.0 you could read about generic covariance and contravariance.
您还可以使用 LINQ Cast() 扩展方法:
这更清晰一些。
此外,如果可能的话,使用 IEnumerable 而不是 IList 通常会更好。
You can also use the LINQ Cast() extension method:
which is a bit clearer.
Also it is often nicer to use IEnumerable instead of IList when possible.