// Cannot change source code
class Base
{
public virtual void Say()
{
Console.WriteLine("Called from Base.");
}
}
// Cannot change source code
class Derived : Base
{
public override void Say()
{
Console.WriteLine("Called from Derived.");
base.Say();
}
}
class SpecialDerived : Derived
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
}
class Program
{
static void Main(string[] args)
{
SpecialDerived sd = new SpecialDerived();
sd.Say();
}
}
Run Code Online (Sandbox Code Playgroud)
结果是:
来自Special Derived.
来自Derived./*这不是预期的*/
从Base调用.
如何重写SpecialDerived类,以便不调用中产阶级"Derived"的方法?
更新: 我想继承Derived而不是Base的原因是Derived类包含许多其他实现.既然我不能在 …
在下面的代码中,我尝试了两种方法来访问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();
}
}
Run Code Online (Sandbox Code Playgroud)
更新 ChrisW发布了这个:
从课外,我不知道任何简单的方法; 但是,也许,我不知道如果尝试反射会发生什么:使用Type.GetMethod方法查找与ParentClass中的方法关联的MethodInfo,然后调用MethodInfo.Invoke
那个答案被删除了.我想知道这个黑客是否可行,只是为了好奇.