簡體   English   中英

獲取屬性類型並轉換泛型

[英]Getting property type and convert 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));
}

盡管我建議您堅持使用@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作為參數。

如果要從字典轉換,請先使用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語句,很容易出現運行時錯誤,這些錯誤從其他方法的上下文來看並沒有多大意義-許多序列化都可以使用非公開設置者,或僅限於字段。 閱讀反射方法使用的重載!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM