如何在C#中找到对象的所有公共字段? [英] How can I find all the public fields of an object in C#?

查看:71
本文介绍了如何在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 ;-)

这篇关于如何在C#中找到对象的所有公共字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆