问题描述
// 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();
}
}
结果是:
从特殊派生中调用.
从派生调用./* 这不是预期的 */
从 Base 调用.
Called from Special Derived.
Called from Derived. /* this is not expected */
Called from Base.
如何重写 SpecialDerived 类,使中间类Derived"的方法不被调用?
How can I rewrite SpecialDerived class so that middle class "Derived"'s method is not called?
更新:我想从 Derived 而不是 Base 继承的原因是 Derived 类包含许多其他实现.既然我不能在这里做 base.base.method()
,我想最好的方法是做以下?
UPDATE:
The reason why I want to inherit from Derived instead of Base is Derived class contains a lot of other implementations. Since I can't do base.base.method()
here, I guess the best way is to do the following?
//无法更改源代码
class Derived : Base
{
public override void Say()
{
CustomSay();
base.Say();
}
protected virtual void CustomSay()
{
Console.WriteLine("Called from Derived.");
}
}
class SpecialDerived : Derived
{
/*
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
*/
protected override void CustomSay()
{
Console.WriteLine("Called from Special Derived.");
}
}
推荐答案
只是想在这里添加这个,因为人们即使经过很多次仍然会回到这个问题.当然这是不好的做法,但(原则上)仍然可以做作者想做的事:
Just want to add this here, since people still return to this question even after many time. Of course it's bad practice, but it's still possible (in principle) to do what author wants with:
class SpecialDerived : Derived
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
var ptr = typeof(Base).GetMethod("Say").MethodHandle.GetFunctionPointer();
var baseSay = (Action)Activator.CreateInstance(typeof(Action), this, ptr);
baseSay();
}
}
这篇关于如何调用 base.base.method()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!