1

i need convert a value of type generic.. but i need get the type of a property for convert... how i can do this ?

public static T ConvertToClass<T>(this Dictionary<string, string> model)
{
    Type type = typeof(T);
    var obj = Activator.CreateInstance(type);
    foreach (var item in model)
    {                              
       type.GetProperty(item.Key).SetValue(obj, item.Value.DynamicType</*TYPE OF PROPERTY*/>());
    }
    return (T)obj;
}
public static T DynamicType<T>(this string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}
  • You should use Json.Net to do this. See here: http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net – Brannon Oct 03 '14 at 18:27

2 Answers2

1

Although I recommend you stick to @Aravol's answer,

If you really need the type of the property, there's a property (sorry for the redundancy) in PropertyInfo that might help you:

public static T ConvertToClass<T>(this Dictionary<string, object> model)
{
    Type type = typeof(T);
    var obj = Activator.CreateInstance(type);
    foreach (var item in model)
    {                              
       PropertyInfo property = type.GetProperty(item.Key);
       Type propertyType = property.PropertyType;
       property.SetValue(obj, item.Value.ConvertToType(propertyType));
    }
    return (T)obj;
}

public static object ConvertToType(this string value, Type t)
{
     return Convert.ChangeType(value, t);
} 

Please note that I modified you DynamicType so it can receive a Type as an argument.

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

If you're converting from a dictionary, start by using a Dictionary<string, object> - everything derives from object, even structs.

this code will work simply by using SetValue because the method takes an object and thus won't care about the type until runtime. Give it the wrong type at runtime though, and it will throw an exception.

public static T ConvertToClass<T>(this Dictionary<string, object> model)
{
    Type type = typeof(T);
    var obj = Activator.CreateInstance(type);
    foreach (var item in model)
    {                              
       type.GetProperty(item.Key).SetValue(obj, item.Value);
    }
    return (T)obj;
}

Be wary of this code - by not using more complex overloads and try-catch statements, it will be very prone to runtime errors that don't make a lot of sense from the context of other methods - lots of serializations are able to use nonpublic setters, or are limited to fields. Read up on the overloads used by the Reflection methods!

David
  • 10,458
  • 1
  • 28
  • 40
  • Yes, show the exception on find a int property..i need convert the item.Value for type of property – Wisner Oliveira Oct 03 '14 at 18:37
  • In this case, you won't need to. Because everything and anything can be passed as an `object` the conversion doesn't happen until runtime. The alternative is unnecessary metacoding – David Oct 03 '14 at 19:55