C# 文法練習(15): 介面

來源:互聯網
上載者:User
介面只聲明、無實現、不能執行個體化;
介面可包含方法、屬性、事件、索引器, 但無欄位;
介面成員都是隱式的 public, 不要使用存取修飾詞;

類、結構和介面都可以繼承多個介面;
繼承介面的類必須實現介面成員, 除非是抽象類別;
類實現的介面成員須是公用的、非靜態.

入門樣本:
using System;interface MyInterface{    int Sqr(int x);}class MyClass : MyInterface{    public int Sqr(int x) { return x * x; }}class Program{    static void Main()    {        MyClass obj = new MyClass();        Console.WriteLine(obj.Sqr(3)); // 9        MyInterface intf = new MyClass();        Console.WriteLine(intf.Sqr(3));        Console.ReadKey();    }}

一個介面得到不同的實現:

using System;interface MyInterface{    int Method(int x, int y);}class MyClass1 : MyInterface{    public int Method(int x, int y) { return x + y; }}class MyClass2 : MyInterface{    public int Method(int x, int y) { return x - y; }}class Program{    static void Main()    {        MyInterface intf1 = new MyClass1();        MyInterface intf2 = new MyClass2();        Console.WriteLine(intf1.Method(3, 2)); // 5        Console.WriteLine(intf2.Method(3, 2)); // 1        Console.ReadKey();    }}

顯示實現介面(介面名.方法):

using System;interface MyInterface1{    void Method();}interface MyInterface2{    void Method();}class MyClass : MyInterface1, MyInterface2{    /* 顯示實現介面不需要存取修飾詞; 但顯示實現的方法只能通過介面訪問 */    void MyInterface1.Method() { Console.WriteLine("MyInterface1_Method"); }    void MyInterface2.Method() { Console.WriteLine("MyInterface2_Method"); }}class Program{    static void Main()    {        MyInterface1 intf1 = new MyClass();        MyInterface2 intf2 = new MyClass();        intf1.Method(); // MyInterface1_Method        intf2.Method(); // MyInterface2_Method        Console.ReadKey();    }}

相關文章

聯繫我們

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