C # inherited function calls
First, let's 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();}}}
Result:
The result shows that:After override is used for rewriting, The called function is the farthest derived function. If new is used for rewriting, the farthest derived function before new is called, that is, the new function is regarded as not overwritten.