C# - 介面_明確介面實作

來源:互聯網
上載者:User

標籤:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5  6 /*---------------------------------------------------------------------------- 7  * 顯式實現介面: 8  *      1. 一個類繼承了兩個以上的介面 9  *      2. 介面中存在相同名稱的方法10  *      3. 通過【介面.方法()】格式在類中顯示實現11  *      4. 將類的執行個體化的對象傳遞給不同的介面對象, 則調用12  *          的是不同介面下各自的方法13  *      5. 類中顯式實現介面的方法前不能使用任何修飾詞14  *      6. 顯示實現的成員都預設為私人, 即不能通過類執行個體化15  *          對象在類外部直接調用, 正確的訪問方式是通過類對16  *          像顯式的轉換為對應的介面, 通過介面來存取方法17 -----------------------------------------------------------------------------*/18 namespace 介面_明確介面實作19 {20     // 定義介面: IChineseGreeting21     interface IChineseGreeting22     {23         void SayHello();24     }25 26     // 定義介面: IAmericanGreeting27     interface IAmericanGreeting28     {29         void SayHello();30     }31 32     // 實現介面: Speaker類33     public class Speaker : IChineseGreeting, IAmericanGreeting34     {35         // 介面: IChineseGreeting 顯示實現36         void IChineseGreeting.SayHello()37         {38             Console.WriteLine("你好!");39         }40 41         // 介面: IAmericanGreeting 顯示實現42         void IAmericanGreeting.SayHello()43         {44             Console.WriteLine("Hello!");45         }46     }47 48     class Program49     {50         static void Main(string[] args)51         {52             Speaker speaker = new Speaker();53             54             IChineseGreeting iChineseG = (IChineseGreeting)speaker;55             iChineseG.SayHello();           // 輸出【"你好"】56 57             IAmericanGreeting iAmericanG = (IAmericanGreeting)speaker;58             iAmericanG.SayHello();        // 輸出【"Hello"】59 60             Console.ReadLine();61         }62     }63 }

 

C# - 介面_明確介面實作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.