【发布时间】:2023-04-02 21:07:01
【问题描述】:
在下面的代码中,我尝试了两种方法来访问methodTwo的父版本,但结果总是2。有没有什么方法可以在不修改这两个类的情况下从ChildClass实例中获取1的结果?
class ParentClass
{
public int methodOne()
{
return methodTwo();
}
virtual public int methodTwo()
{
return 1;
}
}
class ChildClass : ParentClass
{
override public int methodTwo()
{
return 2;
}
}
class Program
{
static void Main(string[] args)
{
var a = new ChildClass();
Console.WriteLine("a.methodOne(): " + a.methodOne());
Console.WriteLine("a.methodTwo(): " + a.methodTwo());
Console.WriteLine("((ParentClass)a).methodTwo(): "
+ ((ParentClass)a).methodTwo());
Console.ReadLine();
}
}
更新 ChrisW 发布了这个:
在课外,我不知道 任何简单的方法;但是,也许,我不 知道如果你尝试会发生什么 反射:使用 Type.GetMethod 查找 MethodInfo 的方法 与方法相关的 ParentClass,然后调用 MethodInfo.Invoke
那个答案被删除了。只是出于好奇,我想知道这种 hack 是否可行。
【问题讨论】:
-
反射技巧不起作用,它也调用了孩子的方法。
标签: c# .net inheritance