How do I reflect over the members of dynamic object?

前端 未结 4 674
感动是毒
感动是毒 2020-11-22 10:51

I need to get a dictionary of properties and their values from an object declared with the dynamic keyword in .NET 4? It seems using reflection for this will not work.

4条回答
  •  无人及你
    2020-11-22 11:24

    Requires Newtonsoft Json.Net

    A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:

    public List GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
    {
        JObject attributesAsJObject = dynamicToGetPropertiesFor;
        Dictionary values = attributesAsJObject.ToObject>();
        List toReturn = new List();
        foreach (string key in values.Keys)
        {
            toReturn.Add(key);                
        }
        return toReturn;
    }
    

    Then you simply foreach like this:

    foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
    {
        dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
        // And
        dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
    }
    

    Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.

提交回复
热议问题