我希望能夠按派生順序調用重寫方法。C# - 按繼承順序調用派生類中的重寫方法
例如在下面的代碼創建一個名爲CallMeThird新類,並調用它的CallMe
方法時,我想它執行的基類中繼承的順序CallMe
方法:
- CallMeFirst
- CallMeSecond
- CallMeThird
There有一對夫婦的事情,我想避免,但:
- 調用在派生類
- 作爲
CallMe
採用OnCallMeFirst
和OnCallMeSecond
仍暴露在派生類和代碼可能會變得混亂base.CallMe
。
是否有一個很好的,乾淨的模式,我可以用於這種情況?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new CallMeThird();
b.CallMe();
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
}
}
}
public abstract class Base
{
public abstract void CallMe();
}
public class CallMeFirst : Base
{
public override void CallMe()
{
Console.WriteLine("I would like to be called first");
}
}
public class CallMeSecond : CallMeFirst
{
public override void CallMe()
{
Console.WriteLine("I would like to be called second");
}
}
public class CallMeThird : CallMeSecond
{
public override void CallMe()
{
Console.WriteLine("I would like to be called third");
}
}
}
責任鏈,也許。真的不能說給這個小小的信息。 –