使用反射查找ArrayList对象属性

Ice*_*ind 1 .net c# reflection

我有一个对象的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.
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 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
    }
}
Run Code Online (Sandbox Code Playgroud)