C # inherited function calls

Source: Internet
Author: User

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.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.