【发布时间】:2013-05-27 06:50:13
【问题描述】:
为什么在下面的代码中会出现编译错误(见注释行)?
public void Test()
{
HashSet<HashSet<Animal>> setWithSets = new HashSet<HashSet<Animal>>();
HashSet<Cat> cats = new HashSet<Cat>();
setWithSets.Add(cats); // Compile error
}
private class Animal { }
private class Cat : Animal { }
VS2012 给了我两个错误,第一个是重要的:
- 错误 2 参数 1:无法从 'System.Collections.Generic.HashSet
' 转换为 'System.Collections.Generic.HashSet ' - 错误 1 'System.Collections.Generic.HashSet
>.Add(System.Collections.Generic.HashSet) 的最佳重载方法匹配' 有一些无效的参数
我的问题是:为什么我不能在“setWithSets”中添加“cats”?
【问题讨论】:
-
您正在查看通用协方差,您可能想查看以下问题:stackoverflow.com/questions/245607/… 或这篇文章(它使用与您实际相同的对象)-> blogs.msdn.com/b/charlie/archive/2008/10/28/…
-
谢谢,会去看看。我还发现了另一个可能使该帖子重复的帖子:stackoverflow.com/questions/6314006/…
标签: c# generics collections hashset