2013-03-22 39 views
2

我試圖編寫一些代碼來遍歷我的業務對象並將其內容轉儲到日誌文件中。使用反射檢測.NET對象上的集合類型屬性

對於這一點,我希望能找到所有的公共屬性和輸出他們的名字和值使用反射 - 我也希望能夠檢測集合屬性和迭代的,太。

假設這樣兩類:

public class Person 
{ 
    private List<Address> _addresses = new List<Address>(); 

    public string Firstname { get; set; } 
    public string Lastname { get; set; } 

    public List<Address> Addresses 
    { 
     get { return _addresses; } 
    } 
} 

public class Address 
{ 
    public string Street { get; set; } 
    public string ZipCode { get; set; } 
    public string City { get; set; } 
} 

我現在有代碼這樣的事情該發現所有的公共屬性:

public void Process(object businessObject) 
{ 
    // fetch info about all public properties 
    List<PropertyInfo> propInfoList = new List<PropertyInfo>(businessObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)); 

    foreach (PropertyInfo info in propInfoList) 
    { 
     // how can I detect here that "Addresses" is a collection of "Address" items 
     // and then iterate over those values as a "list of subentities" here? 
     Console.WriteLine("Name '{0}'; Value '{1}'", info.Name, info.GetValue(businessObject, null)); 
    } 
} 

但我無法弄清楚如何檢測一個屬性(例如Person類中的Addresses)是收集的Address對象?似乎無法找到一個propInfo.PropertyType.IsCollectionType屬性(或類似的東西,會給我,我要找的信息)

我(失敗)嘗試喜歡的東西:

info.PropertyType.IsSubclassOf(typeof(IEnumerable)) 
info.PropertyType.IsSubclassOf(typeof(System.Collections.Generic.List<>)) 

info.PropertyType.IsAssignableFrom(typeof(IEnumerable)) 
+0

馬克,你是否得到它的工作,或你需要任何進一步的信息? – 2013-03-25 07:14:19

+0

@DanielHilgarth:不,看起來你的回答真的覆蓋了它。適用於我。謝謝。對不起,以前忘記接受...... – 2013-03-25 09:10:03

+1

沒問題。只是想確保你有你需要的一切。 – 2013-03-25 09:27:09

回答

2

只是檢查IEnumerable這是由每一個集合來實現,甚至數組:

var isCollection = info.PropertyType.GetInterfaces() 
         .Any(x => x == typeof(IEnumerable)); 

請注意,您可能要添加一些特殊的辦案爲實現此接口的類,但應該還是不喜歡收藏對待。 string會是這樣的情況。

+0

爲什麼不'typeof(IEnumerable).IsAssignableFrom(info.PropertyType)'或'info.PropertyType.GetInterfaces()。Contains(typeof(IEnumerable))'? (我傾向於前者,但尚未驗證實現「IEnumerable」的取消裝箱值類型的值,如[ArraySegment '](http://msdn.microsoft.com/zh-cn/library/1hsbd92d .aspx)in .NET 4.5。 – 2013-03-22 14:43:46

+0

也有可能,你在我的回答中看到的只是我腦海中第一個看到的字符串。 – 2013-03-22 16:24:03

+0

與字符串屬性不符? – 2016-06-02 14:13:51

相關問題