C# 获取属性类型并转换为泛型

C# 获取属性类型并转换为泛型,c#,generics,C#,Generics,我需要转换类型为generic.的值。。但我需要得到转换属性的类型。。。我怎么能做到 public static T ConvertToClass<T>(this Dictionary<string, string> model) { Type type = typeof(T); var obj = Activator.CreateInstance(type); foreach (var item in model) {

我需要转换类型为generic.的值。。但我需要得到转换属性的类型。。。我怎么能做到

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));
}
publicstatict转换类(此字典模型)
{
类型=类型(T);
var obj=Activator.CreateInstance(类型);
foreach(模型中的var项目)
{                              
type.GetProperty(item.Key).SetValue(obj,item.Value.DynamicType());
}
返回(T)obj;
}
公共静态T DynamicType(此字符串值)
{
return(T)Convert.ChangeType(value,typeof(T));
}

如果要从字典转换,请先使用
字典
——所有内容都来自
对象
,甚至结构

此代码只需使用即可工作,因为该方法采用
对象
,因此在运行时之前不会关心类型。但是在运行时给它错误的类型,它会抛出异常

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;
}
publicstatict转换类(此字典模型)
{
类型=类型(T);
var obj=Activator.CreateInstance(类型);
foreach(模型中的var项目)
{                              
type.GetProperty(item.Key).SetValue(obj,item.Value);
}
返回(T)obj;
}

小心这段代码-通过不使用更复杂的重载和try-catch语句,它将非常容易发生运行时错误,而这些错误在其他方法的上下文中没有太多意义-许多序列化都可以使用非公开的setter,或者仅限于字段。阅读反射方法使用的重载

尽管我建议你坚持阿拉沃的答案

如果您确实需要属性的类型,则
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);
} 
publicstatict转换类(此字典模型)
{
类型=类型(T);
var obj=Activator.CreateInstance(类型);
foreach(模型中的var项目)
{                              
PropertyInfo属性=type.GetProperty(item.Key);
类型propertyType=property.propertyType;
SetValue(obj,item.Value.ConvertToType(propertyType));
}
返回(T)obj;
}
公共静态对象ConvertToType(此字符串值,类型t)
{
返回Convert.ChangeType(值,t);
} 


请注意,我修改了您的
DynamicType
,以便它可以接收
类型作为参数。

您应该使用Json.Net来完成此操作。请参见此处:是的,在查找int属性时显示异常。我需要转换项。在这种情况下,您不需要转换属性类型的值。因为所有东西都可以作为
对象传递
,所以转换直到运行时才会发生。另一种选择是不必要的元代码