2011-06-22 52 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吗? –