How to convert object to Dictionary in C#?

前端 未结 15 1791
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 17:58

How do I convert a dynamic object to a Dictionary in C# What can I do?

public static void MyMethod(object obj)
{
    if (typ         


        
15条回答
  •  悲哀的现实
    2020-12-13 18:15

    Assuming key can only be a string but value can be anything try this

    public static Dictionary MyMethod(object obj)
    {
        if (obj is Dictionary stringDictionary)
        {
            return stringDictionary;
        }
    
        if (obj is IDictionary baseDictionary)
        {
            var dictionary = new Dictionary();
            foreach (DictionaryEntry keyValue in baseDictionary)
            {
                if (!(keyValue.Value is TValue))
                {
                    // value is not TKey. perhaps throw an exception
                    return null;
                }
                if (!(keyValue.Key is TKey))
                {
                    // value is not TValue. perhaps throw an exception
                    return null;
                }
    
                dictionary.Add((TKey)keyValue.Key, (TValue)keyValue.Value);
            }
            return dictionary;
        }
        // object is not a dictionary. perhaps throw an exception
        return null;
    }
    

提交回复
热议问题