2012-09-18 101 views
2

Supose這種情況下數據類型屬性裝飾通過反射

public class CustomerMetaData 
{ 


    [DataType(DataType.EmailAddress)]  
    public String EmailAddress {get;set;} 

    [DataType(DataType.Url)]  
    public String UrlUser {get;set;} 

} 

我需要通過這個類的所有屬性的反射數據類型,但廣泛的網絡搜索得到,我沒有找到解決這個類型的數據屬性的任何解決方案。我需要更多的解釋,我不需要知道屬性的數據類型Like,String,Boolean ....)我需要[DataType(DataType .....)]屬性的一部分。

在此先感謝。

一些想法?

回答

4

您需要GetCustomAttributes方法。

這是從內存,但它會去是這樣的:

PropertyInfo[] props = typeof(CustomerMetaData).GetProperties(); 
foreach(PropertyInfo p in props) 
{ 
    object[] attribs = p.GetCustomAttributes(false); 
    // do something with the attributes 
} 

中查找的GetProperties和GetCustomAttributes方法,以確保參數的:如果你的任何性質都是非公開的,你」必須指定一些額外的信息來獲取他們的信息。

+0

感謝您的快速反應! 經過一些修復後,我得到了「attribs」數組內的屬性。 –

+0

爲我的問題添加了完整的解決方案,因爲我很高興與大家分享 –

0

思考了5年後...

PropertyInfo[] props = typeof(CustomerMetaData).GetProperties(); 
foreach(PropertyInfo p in props) 
{ 
    IEnumerable<DataTypeAttibute> dataTypeAttrs = p.GetCustomAttributes<DataTypeAttribute>(false); 
    foreach(var attr in dataTypeAttrs) 
    { 
     DataType dataType = attr.DataType; 
     // do something with the datatype 
    } 
}