C# : Displaying field metadata using System. 反射.GetFields()

标签 c# system.reflection

Possible Duplicate:
Find a private field with Reflection?

我正在尝试使用 System.Reflection.GetFields() 方法显示类的字段名称。

问题是它仅在字段声明为“公共(public)”时才有效。 例如:

class Element
{
    private String id;
    private string a;
    private string b;
    private int c;
    private Dictionary<String, String> dict;

    public Element(String id)
    {
        this.id= id;
    }}

当我尝试调用 System.Reflection.GetFields() 方法时,它不起作用(它返回一个空数组)。但是,如果我将字段的可见性更改为“公共(public)”,它就会起作用..

有人知道如何在不公开的情况下让它发挥作用吗?

谢谢

最佳答案

试试这个:

GetFields(BindingFlags.NonPublic | BindingFlags.Instance)

更新: 以下是当您不带参数调用 GetFields 时场景下发生的情况:

public FieldInfo[] GetFields()
{
   return this.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
}

因此,如您所见,默认情况下不返回私有(private)字段。

顺便说一句,这里是 GetFields() 的描述方法来自msdn:

Returns all the public fields of the current Type. Return Value: An array of FieldInfo objects representing all the public fields defined for the current Type. -or- An empty array of type FieldInfo, if no public fields are defined for the current Type.

关于C# : Displaying field metadata using System. 反射.GetFields(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10350486/

相关文章:

.net - MethodInfo.Invoke 与 Type.InvokeMember?

c# - 使用 C# 反射从类 T 获取属性列表

C# 字符串格式

c# - 使用 Url.Link 在 Web API 中生成 HTTPS 链接

c# - 在 GDI+ 中递归绘制矩形时出现 OutOfMemory 异常

sql-server - 如何在 SSIS 脚本组件中按名称循环遍历列?

vb.net - 使用 System.Reflection 确定所有引用

c# - 在运行时从 C# 检测 F# 记录类型

c# - 如何解析日期后缀为 "th"、 "st"或 "nd"的日期?

c# - XML 压缩兼容 Java 和 C#