Nested Interfaces: Cast IDictionary> to IDictionary>?

后端 未结 2 840
萌比男神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:06

    This may or may not help you, but I thought I'd throw it out as a supplement to Jon's answer.

    If all you need is the dictionary's values, without reference to their keys, you can do this:

    IDictionary> dictionary = Whatever();
    var values = (IEnumerable>)dictionary.Values;
    

    For this to work, you must be using C# 4.0 or later, and TValue must be constrained to be a reference type. Here's the code, slightly refactored, and with comments to explain:

    IDictionary> dictionary = Whatever();
    
    //Values returns an ICollection>
    ICollection> temp1 = dictionary.Values;
    
    //ICollection inherits from IEnumerable
    IEnumerable> temp2 = temp1;
    
    //IEnumerable is covariant
    //There is an implicit reference conversion between IList and IEnumerable
    //So there is an implicit reference conversion between IEnumerable>
    //and IEnumerable>
    IEnumerable> values = temp2;
    

提交回复
热议问题