c# - 在继承 class 中设置私有字段

c# - Set private field in inherit class

好吧,我有一个包含多个 类 的程序,其中一些相互继承。基本布局如下所示:

public class Foo2
{
    public string junk1 = "bleh"; // Not useful
}

public class Foo1 : Foo2
{
    private int num = 2; // I want to access this
    private string junk2 = "yo";
}

public class Foo : Foo1
{
    public string junk3 = "no";
}

现在在另一个我有如下:

public class access // I used Reflection
{
    private Foo2 test = new Foo(); // The only thing important here is that test is Foo2
    
    private void try1() // This was my first attempt(It didn't work)
    {
        Foo tst = (Foo)test;
        tst.GetType().GetField("num", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(tst, 5);
    }
    
    private void try2() // Second attempt also didn't work
    {
        Foo1 tst = (Foo1)test;
        tst.GetType().GetField("num", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(tst, 5);
    }
}

None 我试过的方法都奏效了。

Foo2 不是从 Foo1Foo 派生的,因此它没有派生字段 num。就是这样,期间。

如果你的 tstFoo1 就可以了:

Foo1 test = new Foo1();

test.GetType().GetField("num", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(test, 5);

并且由于私有字段是特定于类型的,在最后一种情况下您需要使用正确的类型:

typeof(Foo1).GetField("num", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(test, 5);