2011-06-22 4 views
1

私はオブジェクトのArrayListを持っています。たとえば:Reflectionを使用して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

'List 'がより適切でしょう。 – 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

これは完璧に動作します。しかし、他のもの、Marcは、プロパティが文字列、int、浮動小数点、小数、またはその他(上記のどれも)であるかどうかを知る方法はありますか? – Icemanind

+1

@icemanindよく 'prop.PropertyType'をチェックすることができますし、より便利には、ほとんどの共通基本型を持つenumである' switch(Type.GetTypeCode(prop.PropertyType)) 'をチェックすることができます。 –

0

それは、このような単純なのです:

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

GetTypeメソッドは、実際の型ではなく、objectを返します。 PropertyInfoの各オブジェクトにはNameプロパティがあります。

1

as演算子を使用すると、Reflectionを使用する必要がなくなります。

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

"このArrayListには常にTestClassオブジェクトが含まれているとは限りません。"(質問から) –

+0

"as TestClass"がありますが、ListにTestClassオブジェクトが含まれていない可能性があります。異なるタイプのオブジェクトをまとめて保持する可能性があります。 – Icemanind

+0

TestClassオブジェクト以外のオブジェクトをキャストするとnullが返されますか? –

関連する問題