如何通过反射获取类及其父类的私有字段? [英] How to get the private fields of class and its parent class(es) by reflection?

查看:97
本文介绍了如何通过反射获取类及其父类的私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类 B 和它的父类 A,都在命名空间域中.

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

  • A 类,有私有字段 a;
  • B 类,有私有字段 b;

然后我在命名空间 Reflect 中有一个 Reflection Util.如果我使用这条线

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

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

要查找所有字段 (a & b),我只得到 b.但是当我将 a 设为 protected 或 public 时,我也会发现它们.

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?

推荐答案

这是 记录在案的行为:

指定 BindingFlags.NonPublic 以在搜索中包含非公共字段(即私有、内部和受保护字段).只返回基类上的受保护和内部字段;不返回基类上的私有字段.

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.

如果您需要获取私有字段,则需要询问基本类型.(使用 Type.BaseType 找到基本类型,然后调用 GetFields.)

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.)

这篇关于如何通过反射获取类及其父类的私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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