C# cast Dictionary to Dictionary (Involving Reflection)

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

    Consider whether casting to and from object really is necessary. I started down that path and stumbled across this article, before realising I could achieve what I needed through generics rather than conversion. For example;

    class DictionaryUtils
    {
        public static T ValueOrDefault(IDictionary dictionary, string key)
        {
            return dictionary.ContainsKey(key) ? dictionary[key] : default(T);
        }
    }
    

    This bit of code is much cleaner and will be faster than the equivalent conversion code shown in other answers.

提交回复
热议问题