2014-10-03 24 views
1

我需要转换类型泛型的值..但我需要获得转换属性的类型...我怎么能做到这一点?获取属性类型和转换通用

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)); 
} 
+0

你应该使用Json.Net来做到这一点。看到这里: http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net – Brannon 2014-10-03 18:27:06

回答

1

虽然我建议你坚持@Aravol的回答,

如果你真的需要的属性的类型,有一个在PropertyInfo属性(遗憾的冗余),可以帮助你:

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); 
} 

请注意,我修改你DynamicType所以它可以接收Type作为参数。

0

如果你从一本字典转换,通过使用Dictionary<string, object>开始 - 一切从object派生,甚至结构。

这段代码只会使用SetValue,因为该方法需要object,因此直到运行时才会关心该类型。尽管在运行时给它错误的类型,它会抛出异常。

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; 
} 

警惕这种代码 - 不使用更复杂的过载和的try-catch语句,否则很容易出现运行错误不从的其他方法的背景下作出了很大的意义 - 很多的序列化能够使用非公共设置器,或者仅限于字段。阅读Reflection方法使用的重载!

+0

是的,显示异常在找到一个int属性..我需要转换项目。价值的属性类型 – 2014-10-03 18:37:57

+0

在这种情况下,你将不需要。因为所有内容和任何东西都可以作为“对象”传递,所以直到运行时才会发生转换。替代方案是不必要的元编码 – David 2014-10-03 19:55:25

相关问题