Function call instance in c inheritance

  • 2020-12-19 21:10:04
  • OfStack

This article gives an example of the function call method in c# inheritance and shares it for your reference. The specific analysis is as follows:

First look at the following code:

using System;
 
namespace Test
{
    public class Base
    {
        public void Print()
        {
            Console.WriteLine(Operate(8, 4));
        }
 
        protected virtual int Operate(int x, int y)
        {
            return x + y;
        }
    }
} namespace Test
{
    public class OnceChild : Base
    {
        protected override int Operate(int x, int y)
        {
            return x - y;
        }
    }
} namespace Test
{
    public class TwiceChild : OnceChild
    {
        protected override int Operate(int x, int y)
        {
            return x * y;
        }
    }
} namespace Test
{
    public class ThirdChild : TwiceChild
    {
    }
} namespace Test
{
    public class ForthChild : ThirdChild
    {
        protected new int Operate(int x, int y)
        {
            return x / y;
        }
    }
} namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Base b = null;
            b = new Base();
            b.Print();
            b = new OnceChild();
            b.Print();
            b = new TwiceChild();
            b.Print();
            b = new ThirdChild();
            b.Print();
            b = new ForthChild();
            b.Print();
        }
    }
}

The operation result is:
12
4
32
32
32

As can be seen from the results: after override is overridden, the function that is called is the farthest derived function, while new is overridden as the furthest derived function before new, that is, new is treated as if it has not been overridden.

Hopefully this article has helped you with your C# programming.


Related articles: