How can I find all the public fields of an object in C#?

こ雲淡風輕ζ 提交于 2019-12-03 23:48:23
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));
    }                           
}

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

You can obtain all the object Fields declared directly in the class with the BindingFlags:

GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)

and all object Fields including inherited with:

GetFields(BindingFlags.Public | BindingFlags.Instance)
public static void ListArrayListMembers(ArrayList list)
{
    foreach (Object obj in list)
    {
        Type type = obj.GetType();
        Console.WriteLine("{0} -- ", type.Name);
        Console.WriteLine(" Properties: ");
        foreach (PropertyInfo prop in type.GetProperties())
        {
            Console.WriteLine("\t{0} {1} = {2}", prop.PropertyType.Name, 
                prop.Name, prop.GetValue(obj, null));
        }
        Console.WriteLine(" Fields: ");
        foreach (FieldInfo field in type.GetFields())
        {
            Console.WriteLine("\t{0} {1} = {2}", field.FieldType.Name, 
                field.Name, field.GetValue(obj));
        }
    }
}

I'd like to mention that looking for IsPublic in the fields is not necessary as type.GetFields() as defined by MSDN states:

Return Value - Type: System.Reflection.FieldInfo[]

An array of FieldInfo objects representing all the public fields defined for the current Type.

Of course, another question would be "why have you got public fields?" - properties being preferable. As an abstraction, note that reflection isn't the only option: it is also possible for a type to expose it's properties on-the-fly at runtime (like how an untyped DataTable/DataView exposes columns as properties).

To support this (while also supporting simple objects), you would use TypeDescriptor:

        foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
        {
            Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
        }

This also allows for numerous extensibility options - for example, vastly speeding up reflection (without changing any code).

    static void ListArrayListMembers(ArrayList list)
    {
        foreach (object obj in list)
        {
            Type type = obj.GetType();
            foreach (FieldInfo field in type.GetFields(BindingFlags.Public))
            {
                Console.WriteLine(field.Name + " = " + field.GetValue(obj).ToString());
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!