【发布时间】: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