如何在C#中找到对象的所有公共字段?

问题描述:

我正在构造一种方法,以接收ArrayList(可能装满了对象),然后列出ArrayList中每个对象的所有字段(及其值).

I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList.

当前我的代码如下:

public static void ListArrayListMembers(ArrayList list)
    {
        foreach (Object obj in list)
        {
            Type type = obj.GetType();
            string field = type.GetFields().ToString();
            Console.WriteLine(field);

        }
    }

当然,我理解此代码的直接问题:如果成功,它只会在ArrayList中的每个对象上打印一个字段.稍后我将解决此问题-现在我很好奇如何获取与对象关联的所有公共字段.

Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.

foreach (Object obj in list) {
    Type type = obj.GetType();

    foreach (var f in type.GetFields().Where(f => f.IsPublic)) {
        Console.WriteLine(
            String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj));
    }                           
}

请注意,此代码需要.NET 3.5才能运行;-)

Note that this code requires .NET 3.5 to work ;-)