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/