2013-03-27 23 views
4

此代碼:TypeDescriptor和子元素

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(lst[0])) 
{ 
    Console.WriteLine(descriptor.Name); 
} 

會寫出我的列表中的所有元素的名稱。即名字/姓氏或永遠。我如何寫出元素的孩子?如果我的列表中包含汽車類型和顏色的汽車,我將如何使用TypeDescriptor來寫出它?

我目前得到的是:

我想是這樣的:

  • 姓氏
  • 汽車:豐田,紅
  • 汽車:三菱,綠色

有誰知道如何做到這一點?

回答

1

PropertyDescriptor -class提供了一種稱爲GetChildProperties(System.Object)的方法。
您應該能夠將當前對象的引用傳遞給方法,並作爲回報接收包含子屬性的另一個集合。
爲了獲得完整的功能,從這個類繼承它甚至是有意義的。

請參閱here以獲取文檔。

1

您需要檢查對象類型,然後在正確的類型時獲取其屬性。

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(lst[0])) 
{ 
    Console.WriteLine(descriptor.Name); 

    if(descriptor.PropertyType == typeof(Car)) 
    { 
     foreach(var child in descriptor.GetChildProperties()) 
     { 
      Console.WriteLine(child.Name); 
     } 
    } 

} 
+0

似乎我不能使用child.Name這樣,即使我現在得到了孩子,我無法找到獲取child1的名稱的方法。我是TypeDescriptor的新手,所以可能有些東西我錯過了...... – 2013-03-27 15:21:59

+0

嘗試將描述符傳遞給GetChildProperties方法。 – taylonr 2013-03-27 15:26:23

+0

仍然沒有運氣。子項包含ComponentType,IsReadOnly,PropertyType。不幫助傳遞lst [0] .Cars。而且我也嘗試過,沒有運氣; – 2013-03-27 16:05:33

0

想想我明白了。只要我有類型我需要兒童的(汽車)我可以這樣做:

foreach (Car c in lst[0].Cars) 
       { 
        PropertyInfo[] properties = car.GetType().GetProperties(); 
        foreach (PropertyInfo item in properties) 
        { 
         string propertyName = item.Name; 
        } 
       }