How to Implement Multi-inheritance in C #: Hybrid + Interface

Source: Internet
Author: User

Has the following structure:Code:

The applyeditable of parent is a virtual method. Child must implement the method differently, that is, override the applyeditable method.

In the above Code, it is obvious that parenta and parentb have repeated code. However, because C # does not support multi-inheritance, the repeated Code cannot be encapsulated in the Multi-inheritance mode.

We only have to follow the flexible path: After my practice, we use the hybrid + interface method. It is better to implement multi-inheritance.

Let's look at the figure directly:

The specific steps are as follows:

  1. Encapsulate the common code in parenta and parentb in basec and use it as an attribute of parent.
  2. Define the method applyeditable to be rewritten to an interface ibasecaction. (In fact, if there is only one method that needs to be rewritten, you do not need to define an interface. You can simply define the delegate variable of an action in basec. Of course, defining interfaces makes it easier to support multiple rewrite methods .)
  3. Let childa and childb implement the ibasecaction interface and implement different codes of applyeditable respectively.
  4. In the constructor of the Child class, pass yourself to the basec for instantiation, that is, this. basec = new basec (this );

I will not post code, completeSource codeFor: http://cid-f73516baeac50992.skydrive.live.com/self.aspx/SharedCode/MultiDerived.zip

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.