简体   繁体   English

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

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

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. 我正在构建一个方法来接收一个ArrayList(可能是完整的对象),然后列出ArrayList中每个对象的所有字段(及其值)。

Currently my code is as follows: 目前我的代码如下:

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

        }
    }

Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. 当然,我理解这段代码的直接问题:如果它有效,它只会在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));
    }                           
}

Note that this code requires .NET 3.5 to work ;-) 请注意,此代码需要.NET 3.5才能工作;-)

You can obtain all the object Fields declared directly in the class with the BindingFlags: 您可以使用BindingFlags获取在类中直接声明的所有对象Fields:

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: 我想提一下,在字段中查找IsPublic不是必需的类型。由MSDN定义的GetFields()表示:

Return Value - Type: System.Reflection.FieldInfo[] 返回值 - 类型:System.Reflection.FieldInfo []

An array of FieldInfo objects representing all the public fields defined for the current Type. 一组FieldInfo对象,表示为当前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). 作为抽象,请注意反射不是唯一的选择:类型也可以在运行时即时公开它的属性(就像无类型的DataTable / DataView如何将列公开为属性)。

To support this (while also supporting simple objects), you would use TypeDescriptor : 要支持这一点(同时还支持简单对象),您可以使用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());
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何找到对 C# 9 记录定义的字段的所有引用? - How can I find all references to fields defined by a C# 9 record? 如何遍历C#对象中的所有字段? - How do I loop through all fields in an object in C#? 如何在C#、. net中找到JObject的必填字段? - How can I find the required fields of a JObject in C#, .net? 我如何从C#中的类对象提取字段 - How can i extract fields from a class object in c# 我可以在C#中访问对象的字段吗 - Can I access fields of an Object in C# UNITY C# - 如何获取标有自定义属性(字段)的 class 实例的所有字段? - UNITY C# - How can I get all the fields of the an instance of a class marked with my custom atribute(the fields)? 当我需要更新 LinQ C#.Net Framework 中的记录时,如何验证所有字段? - How can I validate all fields when I need to update a record in LinQ C# .Net Framework? 如何强制实现 C# 对象的所有字段? - How to force to implement all fields a C# object? 如何找出当前对象是否为对象<T>或对象<T,U>在 C# 中 - How can I find out wether the current object is object<T> or object<T,U> in C# 如何访问 azure function 中的 http 请求的所有字段(在 C# 中解析 JSON)? - How I can access all fields of a http-request in an azure function (parse JSON in C#)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM