Convert Dictionary To Anonymous Object?

后端 未结 7 1420
挽巷
挽巷 2020-11-27 16:33

First, and to make things clearer I\'ll explain my scenario from the top:

I have a method which has the following signature:

public virtual void Send         


        
7条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 16:54

    If you have a class you want to covert the dictionary too, you can use the following to convert a dictionary to an object of that class:

    Example class:

    public class Properties1
    {
        public string Property { get; set; }
    }
    

    The solution:

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Dictionary dict = new Dictionary { { "Property", "foo" } };
    Properties1 properties = serializer.ConvertToType(dict);
    string value = properties.Property;
    

    You could also use a method like this to build the object from the dictionary, obviously this also requires you to have a class.

    private static T DictionaryToObject(IDictionary dict) where T : new()
    {
        T t = new T();
        PropertyInfo[] properties = t.GetType().GetProperties();
    
        foreach (PropertyInfo property in properties)
        {
            if (!dict.Any(x => x.Key.Equals(property.Name, 
                StringComparison.InvariantCultureIgnoreCase)))
                continue;
            KeyValuePair item = dict.First(x => x.Key.Equals(property.Name,
                StringComparison.InvariantCultureIgnoreCase));
            Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
            Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
            object newA = Convert.ChangeType(item.Value, newT);
            t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
        }
        return t;
    }
    

    However if you do not have the class you can create a dynamic object from a dictionary like this:

    private static dynamic DictionaryToObject(Dictionary dict)
    {
        IDictionary eo = (IDictionary)new ExpandoObject();
        foreach (KeyValuePair kvp in dict)
        {
            eo.Add(kvp);
        }
        return eo;
    }
    

    You can use it like this:

    Dictionary dict = new Dictionary {{ "Property", "foo" }};
    dynamic properties = DictionaryToObject(dict);
    string value = properties.Property;
    

提交回复
热议问题