C# cast Dictionary to Dictionary (Involving Reflection)

前端 未结 8 982
无人及你
无人及你 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:13

    Even if you could find some way to express this, it would be the wrong thing to do - it's not true that a Dictionary is a Dictionary, so we definitely don't want to cast. Consider that if we could cast, we could try and put a string in as a value, which obviously doesn't fit!

    What we can do, however, is cast to the non-generic IDictionary (which all Dictionary<,>s implement), then use that to construct a new Dictionary with the same values:

    FieldInfo field = this.GetType().GetField(fieldName);
    IDictionary dictionary = (IDictionary)field.GetValue(this);
    Dictionary newDictionary = 
        dictionary
        .Cast()
        .ToDictionary(entry => (string)entry.Key,
                      entry => entry.Value);
    

    (note that you can't use .Cast here for the reasons discussed here. If you're pre-C# 4, and so don't have dynamic, you'll have to do the enumeration manually, as Gibsnag's answer does)

提交回复
热议问题