// 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();
}
}
Kết quả là:
Được gọi từ Nguồn gốc Đặc biệt.
Được gọi từ Có nguồn gốc. / * điều này không được mong đợi * /
Được gọi từ Cơ sở.
Làm cách nào tôi có thể viết lại lớp SpecialDerived để phương thức của lớp trung gian "Derived" không được gọi?
CẬP NHẬT:
Lý do tại sao tôi muốn kế thừa từ Derived thay vì Base là lớp Derived chứa rất nhiều triển khai khác. Vì tôi không thể làm base.base.method()ở đây, tôi đoán cách tốt nhất là làm như sau?
// Không thể thay đổi mã nguồn
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.");
}
}