use*_*667 9 c# generics dictionary casting covariance
以下为什么不工作?
List<string> castMe = new List<string>();
IEnumerable<string> getFromCast = (IEnumerable<string>)castMe; // allowed.
Dictionary<int, List<string>> castMeDict = new Dictionary<int, List<string>>();
Dictionary<int, IEnumerable<string>> getFromDict = (Dictionary<int, IEnumerable<string>>)castMeDict; // Not allowed
Run Code Online (Sandbox Code Playgroud)
这是Dictionary铸造机制中的一个缺陷,还是我认为应该允许这样做?
谢谢.
Eri*_*ert 22
这是字典铸造机制中的一个缺陷,还是我认为这应该被允许?
在你的思考中.您期望词典在转换中应该是协变的.由于以下原因,它们不是.假设它们是,并推断出可能出错的地方:
Dictionary<int, List<string>> castMeDict =
new Dictionary<int, List<string>>();
Dictionary<int, IEnumerable<string>> getFromDict =
(Dictionary<int, IEnumerable<string>>)castMeDict;
castMeDict[123] = new List<string>();
IEnumerable<string> strings = getFromDict[123]; // No problem!
getFromDict[123] = new string[] { "hello" }; // Big problem!
Run Code Online (Sandbox Code Playgroud)
字符串数组可以转换为IEnumerable<string>但不能转换为List<string>.您只需将不是字符串列表的内容放入只能获取字符串列表的字典中.
在C#中,如果满足以下所有条件,泛型类型可能是协变的或逆变的:
字典中不满足大多数条件 - 它不是接口或委托,它不是可证明安全的,并且类型没有标记为方差安全.因此,字典没有变化.
IEnumerable<T>相比之下,确实符合所有这些条件.你可以转换IEnumerable<string>成IEnumerable<object>C#4.
如果变化的主题让您感兴趣,请考虑阅读我的二十几篇关于这个主题的文章:
http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/
| 归档时间: |
|
| 查看次数: |
3994 次 |
| 最近记录: |