Converting dynamic type to dictionary C#

前端 未结 7 1270
执念已碎
执念已碎 2021-01-01 11:22

I have a dynamic object that looks like this,

 {
    \"2\" : \"foo\",
    \"5\" : \"bar\",
    \"8\" : \"foobar\"
 }

How can I convert this

7条回答
  •  我在风中等你
    2021-01-01 12:22

    You can fill the dictionary using reflection:

    public Dictionary Dyn2Dict(dynamic dynObj)
    {
         var dictionary = new Dictionary();
         foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dynObj))
         {
            object obj = propertyDescriptor.GetValue(dynObj);
            dictionary.Add(propertyDescriptor.Name, obj);
         }
         return dictionary;
    }
    

提交回复
热议问题