开发者

How to get the private fields of class and its parent class(es) by reflection?

开发者 https://www.devze.com 2023-03-03 15:53 出处:网络
I have the class B and its parent class A, both in namespace Domain. 开发者_高级运维Class A, has the private field a;

I have the class B and its parent class A, both in namespace Domain.

Then I have a Reflection Util in namespace Reflect. If I use this line

instanceOfB.GetType().GetFields(BindingFlags.NonPublic 
         | BindingFlags.Public | BindingFlags.Instance );

to to find all fields (a & b), I get only b. But when I make a protected or public I find them too.

What do I need to do to find the private fields of the base class too?


This is the documented behaviour:

Specify BindingFlags.NonPublic to include non-public fields (that is, private, internal, and protected fields) in the search. Only protected and internal fields on base classes are returned; private fields on base classes are not returned.

If you need to get private fields, you'll need to ask the base type. (Use Type.BaseType to find the base type, and call GetFields on that.)


instanceOfB.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );


 public class A
 {
     private int aa;
 }

 public class B
 {
     private int bb;
 }

System.Reflection.FieldInfo[] fields = (new B()).GetType().GetFields(BindingFlags.NonPublic| BindingFlags.Public | BindingFlags.Instance);
0

精彩评论

暂无评论...
验证码 换一张
取 消