简体   繁体   中英

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).

To illustrate why this is the case, just consider what would happen once you've cast to Dictionary<TKey, TBaseValue> . You're still dealing with the original dictionary, which has values that are supposed to only be 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.

Basically, this is C#'s way of preventing you from making a big mistake. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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