简体   繁体   English

演员字典 <TKey, TValue> 作为字典 <TKey, TBaseValue>

[英]Cast Dictionary<TKey, TValue> as Dictionary<TKey, TBaseValue>

Given: 鉴于:

class TKey {}
class TBaseValue {}
class TValue : TBaseValue {}

How can we cast 我们如何铸造

Dictionary<TKey, TValue>

As

Dictionary<TKey, TBaseValue>

And why can it not be done implicitly? 为什么不能隐式地完成呢?

Because Dictionary<TKey, TValue> is not read-only, you can't use covariance here (indeed, the type is declared without the out or in that would allow co-/contra-variance). 由于Dictionary<TKey, TValue>不是只读的,因此您不能在此处使用协方差(实际上,声明类型时不带outin会导致协/反方差)。

To illustrate why this is the case, just consider what would happen once you've cast to Dictionary<TKey, TBaseValue> . 为了说明为什么会这样,只需考虑一下一旦转换为Dictionary<TKey, TBaseValue>会发生什么。 You're still dealing with the original dictionary, which has values that are supposed to only be TValue . 您仍在处理原始字典,该字典的值应该只是TValue But cast that way, you could add some different sub-class of TBaseValue (or even TBaseValue itself), which would violate the rules of the original object's type. 但是以这种方式,您可以添加一些不同的TBaseValue子类(甚至TBaseValue本身),这将违反原始对象类型的规则。

Basically, this is C#'s way of preventing you from making a big mistake. 基本上,这是C#防止您犯大错误的方法。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM