简体   繁体   English

重写基类的实现,以便从继承的基类函数进行的调用也将调用overidden函数

[英]Override the implementation of a base class such that calls from inherited base class functions also call the overidden function

I have to override a function in a base class in such a way that calls to inherited functions also lead to calls to this overridden function instead of the base implementation. 我必须以这样的方式覆盖基类中的函数,即对继承的函数的调用也会导致对该覆盖函数的调用,而不是对基础实现的调用。

class base_class
{
    string abc;
    public int get_1()
    {
        return 1;
    }
    public  int get_number()
    {
        return get_1()+1;
    }
}

class der_class : base_class
{
    public int get_1()
    {
        return 2;
    }
}
class Program
{
    static void Main(string[] args)
    {
        der_class abc = new der_class();
        Console.WriteLine(abc.get_number());
        Console.ReadKey();
    }
}

This prints 2. How can I get the output to be 3 by making the get_number to call overridden get_1? 打印输出2。如何通过使get_number调用覆盖的get_1来使输出为3?

You need the override keyword to actually override a method, otherwise you are hiding it. 您需要override关键字才能实际覆盖方法,否则将其隐藏。

class der_class : base_class
{
    // note the word override here!
    public override int get_1()
    {
        return 2;
    }
}

Also, you need to make the method virtual in the base class: 另外,您需要在基类中使该方法virtual

class base_class
{
    string abc;
    // note the word virtual here!
    public virtual int get_1()
    {
        return 1;
    }
    public  int get_number()
    {
        return get_1()+1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM