"Multiple Inheritance" in c#3.0

Source: Internet
Author: User
Tags abstract inheritance static class


C # 's object system is a single root system, not supporting multiple inheritance of classes, only supporting multiple interface implementations, which in some ways is causing some inconvenience: we often abstract some interfaces in system design and provide an abstract class for the interface as the default implementation, and then the actual class can derive from the abstract class. If a class implements multiple interfaces, then we can only select one abstract class as the ancestor class, and then add the implementation of the other interfaces to the class manually.



This situation has changed in c#3.0, and we can now use the c#3.0 extension method to implement a "restricted multiple inheritance".



c#3.0 introduced an extension method, you can use a static class static method for a class or interface to add a method, the key is to add the method is included implementation, so we can in the c#3.0 for the interface with an implementation of the method declaration, without the need for additional implementation classes! If a class implements more than one such interface, it can achieve a similar effect of multiple inheritance.



Let's test it with code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test35
{
   public interface ITestA{ }
   public static class ITestAHelper
   {
     public static void TestA(this ITestA obj)
     {
       Console.WriteLine("ITestAHelper.TestA");
     }
   }
   public interface ITestB{ }
   public static class ITestBHelper
   {
     public static void TestB(this ITestB obj)
     {
       Console.WriteLine("ITestBHelper.TestB");
     }
   }
   public class Test : ITestA, ITestB
   {
   }
   class Program
   {
     static void Main(string[] args)
     {
       Test obj1 = new Test();
       obj1.TestA();
       obj1.TestB();
       Console.ReadKey();
     }
   }
}


Results of execution:


ITestAHelper.TestA
ITestBHelper.TestB






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.