C # 如何?多繼承

來源:互聯網
上載者:User

C # 如何?多繼承,關鍵在於介面可以寫方法的實現

 

 

namespace Extensions
{
  using System;
  using ExtensionMethodsDemo1;

     public static class Extension
     {
//擴充介面
        public static void MethodB(this IMyInterface myInterface) 
        {
            Console.WriteLine("Extension.MethodB(this IMyInterface myInterface)");
        }
    }
}
namespace ExtensionMethodsDemo1
{
    using System;
    using Extensions;

    public interface IMyInterface
    {
        void MethodB();
    }

    class A : IMyInterface 
    {
        public void MethodB(){Console.WriteLine("A.MethodB()");}
    } 

    class B : IMyInterface
    {
        public void MethodB() { Console.WriteLine("B.MethodB()"); }

    }

    class C : IMyInterface
    {
        public void MethodB() { Console.WriteLine("C.MethodB()"); }

    }

    class ExtMethodDemo
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B();
            C c = new C();

            a.MethodB()
            b.MethodB()
            c.MethodB()

        }
     }
}

 

 

故事篇:

找到這個辦法的故事,,,,一日,閑來無事,來玩玩sp1新特性,entity framework.

媽媽呀,產生實體類啦.

不過,這些實體類屬於充血模型.

習慣了petshop式的貧血模型的我,一下子想到,,,老子提取介面嘛,

然後,貧血模型誕生了.

作為兩個模型的媽, IModelMother...是不是應該為兒子們做一些貢獻呢.

想到了,兩個實體類相互複製屬性的方法 .... 

Code
       public void CopyFrom(IModelMother model)

       {
           this.P1 = model.P1;
           this.P2 = model.P2;
           this.P3 = model.P3;
           this.P4 = model.P4;

       }

 

後來發現,,,這個方法,在兩個實體類中都是相同的實現.

可惜他們媽媽是介面......哎.....

於是給scottgu發了封郵件,大致上說:

老古呀,,  .net怎麼不能多重繼承呢,這樣,一個具有相同實現的方法,放哪呀?????

 

老古回信到,,,,oh,親愛的,我們真是英雄所見略同,

 區別是,我TMD可以驅使一群高人為我解決這個問題.

為瞭解決這個問題,引入了擴充方法,這樣你就可以通過繼承介面來實現多繼承啦.於是乎,產生了本文最上面的程式碼片段

 

 

補充:為什麼他們媽媽不是類???因為EF的實體類有個爹(System.Data.Objects.DataClasses.EntityObject)

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.