2014-02-06 33 views
1

我有幾個域的對象是這樣的:獲得C#的屬性值的多個對象

public class Person() 
{ 
public int age { get; set; } 
public string city{ get; set; } 
} 

public class Company() 
    { 
    public string name{ get; set; } 
    public string address{ get; set; } 
    } 

我有另一個類,如下提到它調用的MyMethod。

public class CallTest() 
{ 
Person p= new Person{age=10,city="dd"}; 
Company c= new Company{name="mynae",address="myaddress"}; 
MyMethod(p); 
MyMethod(c); 
} 

mi.Name給我屬性名稱。但我如何獲得房產價值?

public class MyMethod(object obj) 
{ 
    Type t = obj.GetType(); 
    PropertyInfo prop = t.GetProperty("Items"); 
    foreach (MemberInfo mi in t.GetMembers()) 
      { 
        if (mi.MemberType == MemberTypes.Property) 
        { 
         var x = mi.Name; 
        } 
       } 
} 
+0

可能重複[通過反射獲取通用對象屬性的值](http://stackoverflow.com/questions/5998832/get-value-from-a-generic-object-property-by-reflection) –

回答

2

你需要投MemberInfoPropertyInfo得到它的價值:的

..... 
if (mi.MemberType == MemberTypes.Property) 
{ 
    var x = mi.Name; 
    var value = ((PropertyInfo) mi).GetValue(obj); 
} 
..... 
+0

謝謝,那是有效的。 – Yass

0

要獲得的屬性的值obj.Items你可以使用下面的代碼

public class MyMethod(object obj) 
{ 
    Type t = obj.GetType(); 
    PropertyInfo prop = t.GetProperty("Items"); 
    var x = prop.GetValue(obj, null); 
} 
+0

它不起作用,因爲使用我們必須得到每個財產的價值。當我嘗試你的方法時,它拋出空異常。 – Yass

+0

好吧,我想知道這個問題,我以爲你試圖獲得「物品」的價值。 – Amleth