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

时间:2016-04-09 07:33:27

标签: c# inheritance reflection multiple-inheritance

好的,所以我有一个包含多个类的程序,其中一些类继承了彼此。基本布局如下:

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 frist 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);
    }
}

我试过的方法都没有。请帮忙

哦,对不起我必须使用记事本的代码中的任何错误拼写

由于

1 个答案:

答案 0 :(得分:1)

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