Reputation: 143
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));
}
Upvotes: 1
Views: 352
Reputation: 26281
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.
Upvotes: 1
Reputation: 10708
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!
Upvotes: 0