2011-06-22 55 views
1

我所擁有的是對象的ArrayList,我試圖使用反射來獲取ArrayList中每個對象的每個屬性的名稱。例如:使用反射來查找ArrayList對象屬性

private class TestClass 
{ 
    private int m_IntProp; 

    private string m_StrProp; 
    public string StrProp 
    { 
     get 
     { 
      return m_StrProp; 
     } 

     set 
     { 
      m_StrProp = value; 
     } 
    } 

    public int IntProp 
    { 
     get 
     { 
      return m_IntProp; 
     } 

     set 
     { 
      m_IntProp = value; 
     } 
    } 
} 

ArrayList al = new ArrayList(); 
TestClass tc1 = new TestClass(); 
TestClass tc2 = new TestClass(); 
tc1.IntProp = 5; 
tc1.StrProp = "Test 1"; 
tc2.IntProp = 10; 
tc2.StrPRop = "Test 2"; 
al.Add(tc1); 
al.Add(tc2); 

foreach (object obj in al) 
{ 
    // Here is where I need help 
    // I need to be able to read the properties 
    // StrProp and IntProp. Keep in mind that 
    // this ArrayList may not always contain 
    // TestClass objects. It can be any object, 
    // which is why I think I need to use reflection. 
} 
+0

你使用一個ArrayList,而不是一個[清單(http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx)的原因嗎? – dtb

+0

@dtb - 是的,因爲我的列表可能不一定是TestClass。它可以容納任何物體。 – Icemanind

+1

'列表'會更合適。 – spender

回答

7
foreach (object obj in al) 
{ 
    foreach(PropertyInfo prop in obj.GetType().GetProperties(
     BindingFlags.Public | BindingFlags.Instance)) 
    { 
     object value = prop.GetValue(obj, null); 
     string name = prop.Name; 
     // ^^^^ use those 
    } 
} 
+0

這可能看起來是最好的答案。我現在會嘗試。謝謝 – Icemanind

+0

這工作完美。只有其他的事情,馬克,有沒有辦法知道屬性是一個字符串,int,float,decimal或其他(以上都不是)? – Icemanind

+1

@icemanind,你可以檢查'prop.PropertyType',或者更方便的檢查'switch(Type.GetTypeCode(prop.PropertyType))'這是一個帶有大多數常用基本類型的枚舉。 –

0

它是如此簡單:

PropertyInfo[] props = obj.GetType().GetProperties(); 

GetType方法將返回實際的類型,而不是objectPropertyInfo的每個對象都有一個Name屬性。

1

您可以使用as運算符,這樣就不必使用Reflection。

foreach(object obj in al) 
{ 
    var testClass = obj as TestClass; 
    if (testClass != null) 
    { 
     //Do stuff 
    } 
} 
+0

「請記住,此ArrayList可能不總是包含TestClass對象,它可以是任何對象,」(來自問題) –

+0

您得到「作爲TestClass」,但List可能沒有TestClass對象。它可能會同時持有不同類型的對象 – Icemanind

+0

如果投射TestClass對象以外的對象,它會返回null嗎? –