在一般编程中,有没有办法 "append to a function" 而不是覆盖整个东西?

In general programming, is there a way to "append to a function" and not just override the entire thing?

我目前正在使用 C#,我正在使用一个库,您可以在其中 public override void 但这显然会覆盖整个方法。

是否有 "appending to the method" 的关键字?例如

    class A  
    {  
        public virtual void HelloWorld()  
        {  
            Console.WriteLine("Do this first");  
            Console.ReadLine();  
        }  
    }  

    class B : A  
    {  
        public append void HelloWorld() // <-- Special "append" keyword?
        {  
            Console.WriteLine("Then do this!");  
            Console.ReadLine();  
        }  
    }  

这样 class B : A, HelloWorld() 的输出就是

Do this first
Then do this!

您可以通过 base 关键字在覆盖方法中调用基础实现:

class B : A
{
    public override void HelloWorld() 
    {
        base.HelloWorld(); // will print "Do this first" and wait for console input
        Console.WriteLine("Then do this!");
        Console.ReadLine();
    }
}

您需要先修改代码以调用基础实现。

class B : A  
{  
    public override void HelloWorld()
    {
        base.HelloWorld();
        Console.WriteLine("Then do this!");  
        Console.ReadLine();  
    }  
}

语言对此没有任何概念"append",也不要求您或提供任何方式来强制始终调用基本实现。

您可以在子方法中使用相同的基础工作和额外工作

class A
{
    public void DoSomething()
    {
        //Do Something
    }
}

class B: A
{
    public void DoSomethingExtra()
    {
        base.DoSomething();
        //Do extra things
    }
}

您的要求没有特定的关键字,但您可以从派生 class 调用 base 实现以实现相同的功能。

class A  
{  
    public virtual void HelloWorld()  
    {  
        Console.WriteLine("Do this first");  
        Console.ReadLine();  
    }  
}  

class B : A  
{  
    public override void HelloWorld()
    {  
        base.HelloWorld();
        Console.WriteLine("Then do this!");  
        Console.ReadLine();  
    }  
}

可以通过base关键字

调用父class方法
class A
{
    public virtual void HelloWorld()
    {
        Console.WriteLine("Do this first");
    }
}

class B : A
{
    public override void HelloWorld() // <-- Special "append" keyword?
    {
        base.HelloWorld();
        Console.WriteLine("Then do this!");
    }
}