【发布时间】:2014-11-20 00:13:57
【问题描述】:
给定:
class TKey {}
class TBaseValue {}
class TValue : TBaseValue {}
我们如何投射
Dictionary<TKey, TValue>
作为
Dictionary<TKey, TBaseValue>
为什么不能隐式完成呢?
【问题讨论】:
标签: c# c#-4.0 dictionary casting
给定:
class TKey {}
class TBaseValue {}
class TValue : TBaseValue {}
我们如何投射
Dictionary<TKey, TValue>
作为
Dictionary<TKey, TBaseValue>
为什么不能隐式完成呢?
【问题讨论】:
标签: c# c#-4.0 dictionary casting
因为Dictionary<TKey, TValue> 不是只读的,所以您不能在此处使用协方差(实际上,声明的类型没有out 或in 允许协方差/反方差)。
为了说明为什么会出现这种情况,请考虑一下在您投射到 Dictionary<TKey, TBaseValue> 后会发生什么。您仍在处理原始字典,它的值应该仅为TValue。但是这样转换,您可以添加 TBaseValue 的一些不同子类(甚至是 TBaseValue 本身),这将违反原始对象类型的规则。
基本上,这是 C# 防止您犯大错的方法。 :)
【讨论】: