介面(C# 參考)

來源:互聯網
上載者:User

標籤:instance   interface   des   指南   nbsp   bsp   sse   first   mem   

介面只包含方法、屬性、事件或索引器的簽名。 實現介面的類或結構必須實現介面定義中指定的介面成員。 在下面的樣本,類 ImplementationClass必須實現一個不具有參數並返回 void 的名為 SampleMethod 的方法。

樣本

 1 interface ISampleInterface 2 { 3     void SampleMethod(); 4 } 5  6 class ImplementationClass : ISampleInterface 7 { 8     // Explicit interface member implementation:  9     void ISampleInterface.SampleMethod()10     {11         // Method implementation.12     }13 14     static void Main()15     {16         // Declare an interface instance.17         ISampleInterface obj = new ImplementationClass();18 19         // Call the member.20         obj.SampleMethod();21     }22 }

 

介面可以是命名空間或類的成員,並且可以包含下列成員的簽名:

  • 方法

  • 屬性

  • 索引器

  • 事件

一個介面可從一個或多個基底介面繼承。

當基底類型列表包含基類和介面時,基類必須是列表中的第一項。

實現介面的類可以顯式實現該介面的成員。 顯式實現的成員不能通過類執行個體訪問,而只能通過介面執行個體訪問。

樣本

下面的樣本示範了介面實現。 在此樣本中,介面包含屬性聲明,類包含實現。 實現 IPoint 的類的任何執行個體都具有整數屬性 x 和 y。

 1 interface IPoint 2 { 3    // Property signatures: 4    int x 5    { 6       get; 7       set; 8    } 9 10    int y11    {12       get;13       set;14    }15 }16 17 class Point : IPoint18 {19    // Fields:20    private int _x;21    private int _y;22 23    // Constructor:24    public Point(int x, int y)25    {26       _x = x;27       _y = y;28    }29 30    // Property implementation:31    public int x32    {33       get34       {35          return _x;36       }37 38       set39       {40          _x = value;41       }42    }43 44    public int y45    {46       get47       {48          return _y;49       }50       set51       {52          _y = value;53       }54    }55 }56 57 class MainClass58 {59    static void PrintPoint(IPoint p)60    {61       Console.WriteLine("x={0}, y={1}", p.x, p.y);62    }63 64    static void Main()65    {66       Point p = new Point(2, 3);67       Console.Write("My Point: ");68       PrintPoint(p);69    }70 }71 // Output: My Point: x=2, y=3

 

  

介面(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.