C# cast Dictionary to Dictionary (Involving Reflection)

前端 未结 8 983
无人及你
无人及你 2021-01-04 10:04

Is it possible to cast a Dictionary to a consistent intermediate generic type? So I would be able to cast <

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 10:17

    Following AakashM's answer, the Cast doesn't seem to play ball. You can get around it by using a little helper method though:

    IDictionary dictionary = (IDictionary)field.GetValue(this);
    Dictionary newDictionary = CastDict(dictionary)
                                               .ToDictionary(entry => (string)entry.Key,
                                                             entry => entry.Value);
    
    private IEnumerable CastDict(IDictionary dictionary)
    {
        foreach (DictionaryEntry entry in dictionary)
        {
            yield return entry;
        }
    }
    

    The duck typing in foreach is handy in this instance.

提交回复
热议问题