How to convert object to Dictionary in C#?

前端 未结 15 1792
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  猫巷女王i
    2020-12-13 18:14

    This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):

        private static Dictionary ObjectToDictionary(object source)
        {
            Dictionary result = new Dictionary();
    
            TKey[] keys = { };
            TValue[] values = { };
    
            bool outLoopingKeys = false, outLoopingValues = false;
    
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value is Dictionary.KeyCollection)
                {
                    keys = ((Dictionary.KeyCollection)value).ToArray();
                    outLoopingKeys = true;
                }
                if (value is Dictionary.ValueCollection)
                {
                    values = ((Dictionary.ValueCollection)value).ToArray();
                    outLoopingValues = true;
                }
                if(outLoopingKeys & outLoopingValues)
                {
                    break;
                }
            }
    
            for (int i = 0; i < keys.Length; i++)
            {
                result.Add(keys[i], values[i]);
            }
    
            return result;
        }
    

提交回复
热议问题