C# 中的接口和列表
我对以下接口和类有问题:
public interface IRelated
{
}
public class BaseItem:IRelated
{
public string Name{get;set;}
public List<IRelated> RelatedItems{get;set;}
}
现在,当我尝试在其他类中执行以下操作时,它会给我一个编译错误:
List<IRelated> listofrelateditems=new List<BaseItem>();
无法隐式转换类型
List
到List
接口的原因是将来也许我会有另一个类可以与这个 BaseItem 相关。
im having issues with the following interface and a class:
public interface IRelated
{
}
public class BaseItem:IRelated
{
public string Name{get;set;}
public List<IRelated> RelatedItems{get;set;}
}
Now when i try to do in other classes the following it gives me a compilation error:
List<IRelated> listofrelateditems=new List<BaseItem>();
Cannot implicity convert type
List<BaseItem>
toList<IRelated>
The reason of the interface is that in the future maybe i will have another class that can be Related to this BaseItem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你就是不能这样做 - 即使 .NET 4 中的通用协方差也无法帮助你,因为
List
是一个类,甚至IList
是不变的,因为它有T
进来和出去。正是因为您将来可能会有一个新的
IRelated
实现,所以您不能这样做。考虑一下:其中
OtherRelatedItem
实现IRelated
但不从BaseItem
派生。现在您已经有了一个List
,其中包含BaseItem
以外的内容!换句话说,它破坏了类型安全。基本上,您必须创建一个
List
而不是List
。有关通用方差的更多信息以及为什么它有时适用有时不适用,请访问 NDC 2010 视频页面搜索“variance”即可找到我去年就该主题进行的演示的视频。
You just can't do that - even the generic covariance in .NET 4 won't help you, because
List<T>
is a class and evenIList<T>
is invariant as it hasT
coming "in" as well as going out.It's precisely because you might have a new implementation of
IRelated
in the future that you can't do that. Consider:where
OtherRelatedItem
implementsIRelated
but doesn't derive fromBaseItem
. Now you've got aList<BaseItem>
which contains something other than aBaseItem
! In other words, it breaks type safety.Basically you'll have to create a
List<IRelated>
instead of aList<BaseItem>
.For more on generic variance and why it's sometimes applicable and sometimes not, go to the NDC 2010 videos page and search for "variance" to find the video of a presentation I gave on the topic last year.
就像您自己所说:您可能有另一个可以是 IRelated 的类。如何将此类的实例添加到
List
中?你必须写:
Like you yourself said: You may have another class that can be
IRelated
. How are you going to add an instance of such a class to aList<BaseItem>
?You will have to write:
更改为:
Change to: