从基类反射私有字段 [英] Reflecting a private field from a base class

查看:29
本文介绍了从基类反射私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结构如下:

我的课堂:SuperClass2

MyClass : SuperClass2

SuperClass2 : SuperClass1

SuperClass2 : SuperClass1

superClass2 在 Product.Web 中,SuperClass1 在 .NET System.Web 程序集中

superClass2 is in Product.Web and SuperClass1 is in the .NET System.Web assembly

我正在尝试将一个值强加到 SuperClass1 上的私有 bool 字段中.但无论我尝试什么,我都无法从反射中恢复字段.

I'm trying to force a value into a private bool field on SuperClass1. But not matter what I try I cannot get the fields to come back from reflection.

我将以下代码与不同的 BindingFlag 组合一起使用,但到目前为止没有任何效果.SuperClass1 是一个抽象类.

I'm using the following code with different BindingFlag combinations but nothing has worked so far. SuperClass1 is an abstract class.

((SuperClass1)this).GetType().GetFields(System.Reflection.BindingFlags.NonPublic);

注意事项:当我使用 GetProperties() 时,我会得到一个不错的大列表,但是当我指定任何 bindingflags 时,即使有匹配的属性,我也什么也得不到.怎么回事?

Notes: When I use GetProperties() I get back a nice big list but when I specify any bindingflags I get nothing even though there are matching properties. Whats the deal?

此外,该字段未标记为内部

Also, the field is not marked internal

显然我会使用 GetField(string name, BindingFlags) 但我什至无法让 GetFlags() 工作.

Obvisouly I would be using GetField(string name, BindingFlags) but I can't even get GetFlags() to work.

更新:我已经尝试按照建议添加 BindingFlags.Instance 但它不起作用(无论如何都符合预期).我取回 2 个来自 SuperClass1 继承的类的字段.与 GetField(string name, Flags) 一起使用时返回 null

Update: I've tried adding BindingFlags.Instance as suggested but it doesn't work (as expected anyway). I get back 2 fields that are coming from the class SuperClass1 inherits from. Returns null when used with GetField(string name, Flags)

这是我试图获取字段的基类代码

Here is the code for the base class I'm trying to get the field for

public abstract class BaseValidator : Label, IValidator
  {
    private bool propertiesChecked;
...
}

推荐答案

可以在继承链中手动上去获取基础字段:

You can manually go up in the inheritance chain to get the base fields:

给定这些类:

class SuperClass1
{
    private int myField;
}

class SuperClass2 : SuperClass1
{
}

class MyClass : SuperClass2
{

}

这应该有效:

var myObj = new MyClass();
var myField = typeof(MyClass).BaseType
                             .BaseType
                             .GetField("myField", BindingFlags.Instance | BindingFlags.NonPublic);

在这个 SO 答案中有一个更通用的解决方案:没有从 GetType() 获取字段.GetFields 和 BindingFlag.Default

There's a more generic solution in this SO answer: Not getting fields from GetType().GetFields with BindingFlag.Default

这篇关于从基类反射私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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