相关疑难解决方法(0)

.NET 4中的IDictionary <TKey,TValue>不是协变的

IDictionary<TKey, TValue>在.NET 4/Silverlight 4中不支持的协方差,即我不能做

IDictionary<string, object> myDict = new Dictionary<string, string>();
Run Code Online (Sandbox Code Playgroud)

类似于我IEnumerable<T>现在可以做的事情.

可能归结为KeyValuePair<TKey, TValue>不协变.我觉得至少应该在字典中允许协方差值.

这是一个错误还是一个功能?它会不会来,也许在.NET 37.4中?

更新(2年后):

IReadOnlyDictionary<TKey, TValue>在.NET 4.5中会有一个,但它也不会是协变的:·/,因为它派生自IEnumerable<KeyValuePair<TKey, TValue>>,而KeyValuePair<TKey, TValue>不是一个接口,因此不能协变.

BCL团队将不得不重新设计出来并使用一些ICovariantPair<TKey, TValue>代替.this[TKey key]对于协变接口也不可能使用强类型索引器.类似的结束只能通过在GetValue<>(this IReadOnlyDictionary<TKey, TValue> self, TKey key)某个地方放置一个扩展方法来实现,这种方法在内部必须调用一个实际的实现,这可能看起来像一个非常混乱的方法.

.net dictionary .net-4.0 covariance

58
推荐指数
3
解决办法
7743
查看次数

C#方差问题:将List <Derived>分配为List <Base>

请看以下示例(部分取自MSDN博客):

class Animal { }
class Giraffe : Animal { }

static void Main(string[] args)
{
    // Array assignment works, but...
    Animal[] animals = new Giraffe[10]; 

    // implicit...
    List<Animal> animalsList = new List<Giraffe>();

    // ...and explicit casting fails
    List<Animal> animalsList2 = (List<Animal>) new List<Giraffe>();
}
Run Code Online (Sandbox Code Playgroud)

这是一个协方差问题吗?这将在未来的C#版本中得到支持吗?是否有任何聪明的解决方法(仅使用.NET 2.0)?

c# covariance

54
推荐指数
4
解决办法
2万
查看次数

标签 统计

covariance ×2

.net ×1

.net-4.0 ×1

c# ×1

dictionary ×1