简体   繁体   English

Type.GetFields返回公共字段的空System.Reflection.FieldInfo数组

[英]Type.GetFields return an empty System.Reflection.FieldInfo array for public fields

I have a class that contains only a number of public fields of rather standard types. 我有一个只包含相当标准类型的公共字段的类。 The call myObject.GetType().GetFields() returns an empty array. 调用myObject.GetType().GetFields()返回一个空数组。

What can the problem be? 可能是什么问题?

UPDATE: I am sorry folks, the problem was that I was using a class exposed by WCF service. 更新:对不起大家,问题是我正在使用WCF服务公开的类。 The original class (say A) and the exposed (WcfReference.A) are different classes. 原始类(例如A)和公开类(WcfReference.A)是不同的类。 A's members become private fields in WcfReference.A and exposed as properties. A的成员成为WcfReference.A中的私有字段,并作为属性公开。

Perhaps the question should be deleted. 也许应该删除该问题。

GetFields() without arguments will return the public Fields (not properties as @Kenneth Ito noticed) of your type. 没有参数的GetFields()将返回您类型的公共字段(不是@Kenneth Ito注意到的属性)。

example

public class Test {
   public string var_;//I'm a public field, I'll be returned
   private int id_; //I'm a private field, you'll have to do more to get me
   public int Id {get { return id_;} set {id_=value;}} //I'm a property, I don't feel concerned
}

if you do 如果你这样做

var test = new Test();
test.GetType().GetFields();

will return an array with one item : var_ 将返回一个包含一项的数组:var_

In older versions of .NET (I'm adding functionality to a 1.1 project, pity me), the default method GetFields() will return an empty array. 在旧版本的.NET(我要向1.1项目中添加功能,对不起),默认方法GetFields()将返回一个空数组。 After 1.1, they updated this method to include all public properties. 在1.1之后,他们更新了此方法以包括所有公共属性。 I don't know why they made this change, as there is already a GetProperties() method which will do the same thing. 我不知道他们为什么要进行此更改,因为已经有可以执行相同操作的GetProperties()方法。

This method is the way to get at private fields, so knowledge of how to work with it is critical. 这种方法是进入私有领域的方法,因此了解如何使用它至关重要。 There is an overload for the method GetFields(BindingFlags flags) . 方法GetFields(BindingFlags flags)的重载。 This uses a combination of BindingFlags to determine which fields you want from your object. 这使用BindingFlags的组合来确定要从对象中获取哪些字段。

So if you want instance private fields, you would call: 因此,如果您想要实例私有字段,则可以调用:

GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

If you only want public static properties, you would call: 如果只需要公共静态属性,则可以调用:

GetFields(BindingFlags.Static | BindingFlags.Public);

You can also continue to combine them for all static fields: 您还可以继续为所有静态字段组合它们:

GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

There are many other types of BindingFlags , so check out the MSDN page linked above for any others you might need. 还有许多其他类型的BindingFlags ,因此请查看上面链接的MSDN页面,以获取您可能需要的其他任何信息。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM