【问题标题】:c# - Set private field in inherit classc# - 在继承类中设置私有字段
【发布时间】:2016-04-09 07:33:26
【问题描述】:

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

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

我试过的方法都没有奏效。

【问题讨论】:

  • 你不能这样投,你的代码会在(Foo)test或(Foo1)test上抛出一个InvalidCastException。
  • 您创建了一个 Foo2 的实例。该类不包含名为 num 的成员。绝对没有办法写入该字段。反射也无济于事。
  • 如果您只想像标题所说的那样在派生类中访问此字段(您的代码不会尝试在派生类中访问)通过实现一个受保护的属性来控制访问您的领域。在这种情况下,您不需要反思。
  • 也想过,但protected 在从课堂外访问字段/属性时也无济于事。 @Verarind
  • 伙计们,我在上面的代码中修复了错误,所以是的

标签: c# inheritance reflection multiple-inheritance


【解决方案1】:

Foo2 不是从 Foo1 或 Foo 派生的,因此它没有派生字段 num。就是这样,句号。

如果您的 tst 是 Foo1,它会起作用:

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

【讨论】:

  • 当我测试是 Foo1 时,当我测试是 Foo 时它返回的结果相同,我成功地从 Foo 修改了东西,它工作但这是第一次在 Foo1 上尝试并失败
  • 也许您的示例代码是错误的,但这永远不会以这种方式工作。如果test 是Foo 或Foo1 但不是Foo2,它将起作用。
  • 我刚刚仔细检查了它是否完全一样,如果我告诉你我统一使用 .Net framework 2.0 可能会有所帮助,但我怀疑这会产生任何影响
  • 不,没关系。您的继承(或缺少继承)导致了问题。
  • 好的,我在上面的代码中修复了错误,您现在可以帮忙。对此感到抱歉
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2013-01-09
  • 2020-10-25
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
相关资源
最近更新 更多