C#: Any way to skip over one of the base calls in polymorphism?

后端 未结 7 1286
一个人的身影
一个人的身影 2021-01-17 16:34
class GrandParent
{
    public virtual void Foo() { ... }
}

class Parent : GrandParent
{
    public override void Foo()
    {
       base.Foo();

       //Do additi         


        
7条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 17:00

    We had exactly this scenario on a large project where the derived methods were called from various locations. Due to change management and QA scripts not to be broken, among other constraints, "drastic" refactoring and class re-structuring are not always possible on a large mature project. Also we did not want to override the method and exclude all base functionality. Most solutions seen elsewhere, looked a bit clumsy, but the solution from Josh Jordan on How to call base.base was quite useful.

    However we followed the approach below (which I see now is very similar to what Dan Abramov propose).

    public class Base
    {
        public virtual void Foo()
        {
            Console.WriteLine("Hello from Base");
        }
    }
    
    public class Derived : Base
    {
        public override void Foo()
        {
            base.Foo();
            Console.WriteLine("Text 1");
            WriteText2Func();
            Console.WriteLine("Text 3");
        }
    
        protected virtual void WriteText2Func()
        {
            Console.WriteLine("Text 2");
        }
    }
    
    public class Special : Derived
    {
        public override void WriteText2Func()
        {
            //WriteText2Func will write nothing when method Foo is called from class Special.
            //Also it can be modified to do something else.
        }
    }   
    

提交回复
热议问题