在一般编程中,有没有一种方法可以“附加到函数”而不仅仅是覆盖整个事物?

时间:2020-06-15 11:51:39

标签: c# inheritance keyword

我目前正在使用C#,并且正在使用一个可以public override void进行访问的库,但这显然会覆盖整个方法。

是否存在用于“附加到方法”的关键字?例如

    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!

5 个答案:

答案 0 :(得分:5)

您可以通过base关键字调用父类方法

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!");
    }
}

答案 1 :(得分:4)

您可以通过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();
    }
}

答案 2 :(得分:2)

您要查询的内容没有特定的关键字,但是您可以从派生类中调用base实现以实现相同的功能。

InnerText

答案 3 :(得分:1)

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

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

语言没有这个“附加”的概念,也不需要您提供任何方法或提供任何方法来强制始终调用基本实现。

答案 4 :(得分:0)

您可以在基础方法中使用相同的作品,而在孩子的方法中可以使用额外的作品

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

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