如何转换 IList到 IList其中 SomeObject 在 C# 4.0 中使用协方差实现 ISomeInterface
如何将 IList 转换为 IList,其中 SomeObject 使用 C# 4.0 中的协方差实现 ISomeInterface
我有类似于以下内容的内容
IList<Items> GetItems;
IList<IItems> items = GetItems() as IList<IItems>;
,但 items 为 null;
这里的答案是 4.0 之前的版本:
How to Convert IList to IList where SomeObject implements ISomeInterface using covariance in C# 4.0
I have something similar to following
IList<Items> GetItems;
IList<IItems> items = GetItems() as IList<IItems>;
but items is null;
the answer here was for pre 4.0:
Converting an array of type T to an array of type I where T implements I in C#
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不简单地使用
why not simply use
为了使其按照您的想法工作,我相信 IList 必须被声明为协变,而不是列表中的项目。并且IList不支持协方差。更新为支持协变的唯一 .NET 接口有:
这来自 http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
For this to work as you are thinking then I believe IList would have to be declared as covariant, not the items in the list. And IList does not support covariance. The only .NET interfaces that were updated to support covariance are:
This from http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
从技术上讲,以下内容可行,但我不认为这正是您正在寻找的......
Technically, the following will work, but I don't think this is exactly what you're looking for...