问题描述
我在 C# 中将多态性与 int
列表一起使用时遇到问题。我需要“外部”列表才能添加/删除“内部”列表,但“内部”列表不需要更改。所以我考虑使用变量类型ICollection<IEnumerable<int>>
。
现在,我现在知道这有效:
IEnumerable<int> someList = new List<int>(); //Works fine
现在我也知道这有效:
ICollection<int> anotherList = new List<int>(); //Also works fine
然而,我惊讶地发现这会引发编译错误:
ICollection<IEnumerable<int>> listOfLists = new List<List<int>>(); //Doesn't compile
不能隐式转换类型
'System.Collections.Generic.List
而且我也惊讶地发现它编译得很好:
IEnumerable<ICollection<int>> anotherListOfLists = new List<List<int>>(); //Works fine (?)
我知道一个简单的 List<List<int>> listOfListsWithoutPolymorphism = new List<List<int>>();
会起作用,但我的问题是:
- 第三个和第四个例子有什么区别?
- 如何使用多态实现我需要的东西(比如
ICollecion<IEnumerable<int>>
)?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)