2011-04-12 89 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