如何将项目添加到通用集合中?
给定:
public static void DoStuff<T>(ICollection<T> source)
{
Customer c = new Customer();
....
source.Add(c);
}
除了 c
不是
类型。
那么如何将项目添加到通用集合中?
我尝试有:
public static void DoStuff(ICollection<Human> source)
{
Customer c = new Customer();
....
source.Add(c);
}
但我不使用它,因为没有人可以调用DoStuff
:
ICollection<Customer> c;
DoStuff(c); <---error
因为有关协方差的东西,而.NET没有意识到Customer
源自 Human
:
class Customer : Human {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只是为了让您知道为什么会收到该错误,
ICollection
无法传递给ICollection
,因为它们不是同样的事情。可以这样想,如果您有一个ICollection
,如果Deadbeat
派生自Add(new Deadbeat()) >人类。
关于如何避免泛型问题的其他答案解决了您的问题(因此他们应该获得答案):
但我只是想抛出这个答案来解释为什么您会收到该错误。想一想,如果您可以将
Customer
集合作为Human
集合传递,那么您将可以添加任何类型的人类,而这将违反原始集合。因此,即使
Customer
扩展了Human
,这并不意味着ICollection
扩展了ICollection
并且ICollection
不是协变/逆变,因为它对in
和in
都使用T
out
操作。Just so you know why you get that error, an
ICollection<Customer>
can not be passed to anICollection<Human>
because they are not the same thing. Think of it this way, if you had anICollection<Human>
you couldAdd(new Deadbeat())
ifDeadbeat
derived fromHuman
.The other answers on ways to avoid your issue with a generic solves your problem (so they should get the answer credit):
but I just wanted to throw this answer out to explain why you get that error. Think of it, if you could pass a collection of
Customer
as a collection ofHuman
, it would let you add ANY kind of human, and this would violate the original collection.Thus, even though
Customer
extendsHuman
, this does not mean thatICollection<Customer>
extendsICollection<Human>
andICollection<T>
is not covariant/contravariant because it usesT
for bothin
andout
operations.应该是:
此外,您还必须添加
new
约束保证T
具有公共无参数构造函数:should be just:
Also you will have to add the
new
constraint to guarantee thatT
has a public parameterless constructor:你可能想要这样的东西:
You probably want something like this: