Nested Interfaces: Cast IDictionary> to IDictionary>?

后端 未结 2 812
萌比男神i
萌比男神i 2021-01-22 07:17

I would think it\'s fairly straightforward to cast an IDictionary> object to an IDictionary

2条回答
  •  终归单人心
    2021-01-22 08:08

    I would think it's fairly straightforward to cast an IDictionary> object to an IDictionary>

    Absolutely not. It wouldn't be type-safe. Here's an example of why not:

    // This is fine...
    IDictionary> dictionary = new Dictionary>();
    
    // Suppose this were valid...
    IDictionary> badDictionary = dictionary;
    
    // LinkedList doesn't implement IList
    badDictionary["foo"] = new LinkedList();
    
    // What should happen now?
    IList bang = dictionary["foo"];
    

    As you can see, that's going to cause problems - we'd be trying to get a LinkedList out when we expect all the values to implement IList. The point of generics is to be type-safe - so which line would you expect to fail? The first, third and fourth lines look pretty clearly valid to me - so the second one is the only one which can fail to compile, and it does...

    Now in some cases, it can be done safely. For example, you can convert (in C# 4) from IEnumerable to IEnumerable because IEnumerable only uses T in "output" positions.

    See MSDN for more details.

    EDIT: Just to clarify - it's easy to create a new dictionary with a copy of the existing key/value pairs, e.g. using link:

    var copy = original.ToDictionary>(pair => pair.Key,
                                                                pair => pair.Value);
    

    You just need to be aware that you now have two separate dictionaries.

    提交回复
    热议问题