2011-04-12 87 views
0

在我的代碼中,我在for循環中獲取對象的類型(Party對象),並獲取特定屬性「firstname」的屬性信息。 Party []集合中的所有對象都返回相同的類型,所以我希望在while循環中只獲取一次以外的類型,並且仍然需要能夠從正確的聚會對象中獲取屬性「firstname」。 可以這樣做嗎?謝謝你的幫助。如何在運行時獲取對象集合中的對象類型?

public List<Party> Parties { get; set; } 

PropertyInfo info = null; 

i = 1 
do 
{ 

    foreach (Field field in TotalFields) 
    { 

     info = Parties[i - 1].GetType().GetProperty("firstname"); 

     //some other code here 

    } 
i++; 
} while (i <= Parties.Count); 

回答

1

當您通過PropertyInfo對象得到一個屬性的值,你需要傳遞從中獲取值的對象實例。這意味着,你可以重複使用相同的PropertyInfo實例幾個對象,因爲它們是同一類型的PropertyInfo是爲創建:

// Note how we get the PropertyInfo from the Type itself, not an object 
// instance of that type. 
PropertyInfo propInfo = typeof(YourType).GetProperty("SomeProperty"); 

foreach (YourType item in SomeList) 
{ 
    // this assumes that YourType.SomeProperty is a string, just as an example 
    string value = (string)propInfo.GetValue(item, null); 
    // do something sensible with value 
} 

你的問題被標記爲C#3,但出於完整性它的價值提到在C#4中使用dynamic可以使其更簡單:

foreach (dynamic item in SomeList) 
{ 
    string value = item.SomeProperty; 
    // do something sensible with value 
} 
+0

非常感謝。我想我現在明白了。 – Jyina 2011-04-12 18:09:16