2011-05-09 80 views
1

我需要從嵌套屬性中獲取值。我需要從嵌套屬性中獲取值

在MainClass我有一個學生屬性是學生類的類型。

MainClass obj = new MainClass(); 

obj.Name = "XII"; 
obj.Students = new List<Students>() 
    { 
     new Students() { ID = "a0", Name = "A" }, 
     new Bridge() { ID = "a1", Name = "B" } 
    }; 

Type t = Type.GetType(obj.ToString()); 
PropertyInfo p = t.GetProperty("Students"); 

object gg = p.GetValue(obj, null); 
var hh = gg.GetType(); 
string propertyType = string.Empty; 

if (hh.IsGenericType) 
    { 
     string[] propertyTypes = hh.ToString().Split('['); 
     Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1)); 
     foreach (PropertyInfo pro in gggg.GetProperties()) 
      { 
       if (pro.Name.Equals("Name")) 
       { 
        // Get the value here 
       } 
      } 
    } 
+0

爲什麼不使用List的'Find'方法? – V4Vendetta 2011-05-09 06:49:20

+0

你究竟在找什麼?是真的需要反思嗎?什麼是「Bridge」類? – SWeko 2011-05-09 06:52:10

回答

2

首先,

Type t = Type.GetType(obj.ToString()); 

是錯誤的。這隻適用於類沒有重載ToString()方法的情況,如果有的話,它將在運行時崩潰。幸運的是,每一類有一個的GetType()梅託德(它的定義上的對象,所以Type t = obj.GetType()是正確的代碼。

二,

string[] propertyTypes = hh.ToString().Split('['); 
Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1) 

是一個可怕的方式獲得的類型指定的泛型類型,因爲有一個方法GetGenericArguments,做的是你,所以這段代碼可以與

Type[] genericArguments = hh.GetGenericArguments(); 
Type gggg = genericArguments[0]; 

現在到了真正的問題來改變,訪問的列表項。要做到這一點,最好的辦法是使用索引([])的List<>班。在c#中,當你定義一個索引器時,它會自動轉移到名爲Item的屬性,我們可以使用該屬性來提取我們的值(Item名稱可以從類型定義中推斷出來,但大多數情況下,它可以被硬編碼)

PropertyInfo indexer = hh.GetProperty("Item"); // gets the indexer 

//note the second parameter, that's the index 
object student1 = indexer.GetValue(gg, new object[]{0}); 
object student2 = indexer.GetValue(gg, new object[]{1}); 

PropertyInfo name = gggg.GetProperty("Name"); 
object studentsName1 = name.GetValue(student1, null); // returns "A" 
object studentsName2 = name.GetValue(student2, null); // returns "B" 
0

覆蓋兩個StudentsBridgeEquals方法,然後用Find或使用LINQ

+0

其實這是不正確的。 'Type.GetType'需要一個類的名字,然後返回該字符串的類型,所以你的第二行不會編譯(通常)。第一行是sintaxically正確的,但很愚蠢,因爲類可以覆蓋'ToString()'方法,'obj.GetType()'是簡短而正確的版本。 – SWeko 2011-05-09 07:01:00

+0

@SWeko感謝您的糾正。 – abhilash 2011-05-09 07:02:46

+2

@Sekeko:語法上 – Svish 2011-05-09 07:12:37