C#–介面的實現

來源:互聯網
上載者:User

介面:

    1. 不允許使用存取修飾詞,所有介面成員都是公用的.
    2. 介面成員不能包含代碼體.
    3. 介面不能定義欄位成員.
    4. 介面成員不能使用關鍵字static,vritual,abstract,sealed來定義.
    5. 類型定義成員是禁止的.

如果要隱藏繼承了介面中的成員,可以用關鍵字new來定義它們.

public interface IMyInterface{    void DoSomething();}public interface IMyDeInterface : IMyInterface{    new void DoSomething();}

在介面中定義的屬性可以確認訪問塊get和set中的哪一個能用於該屬性.

public interface IMyInterface{    int myNum    {        get;        set;    }}

注意:介面中不能指定欄位.

在類中實現介面:

當一個類實現一個介面時,可以使用abstract或virtual來執行介面的成員,而不能使用static或const.

一個類的如果實現了一個借口,那麼這個類的衍生類別隱式的支援該介面.

顯式執行介面成員

介面成員可以由類顯式的執行.如果這麼做,那麼這個成員只能通過介面來訪問.而不能通過類來訪問.

public interface IMyInterface{    void DoSomeThing();}public class MyClass : IMyInterface{        void IMyInterface.DoSomeThing()    {        throw new NotImplementedException();    }}
 
    protected void Page_Load(object sender, EventArgs e)    {        //此時mc是沒有方法的.        MyClass mc = new MyClass();        //此時my有個方法DoSomeThing()        IMyInterface my = mc;        my.DoSomeThing();    }
 
隱式執行介面成員
預設都是隱式執行介面成員.
public interface IMyInterface{    void DoSomeThing();}public class MyClass : IMyInterface{        public void DoSomeThing()    {        throw new NotImplementedException();    }}
 
    protected void Page_Load(object sender, EventArgs e)    {        MyClass mc = new MyClass();        mc.DoSomeThing();    }

 

類實現介面屬性

public interface IMyInterface{    int MyNum    {        get;    }}public class MyClass : IMyInterface{    protected int myNum;    public int MyNum    {        get        {             return myNum;         }        set        {            myNum = value;        }    }}
 
    protected void Page_Load(object sender, EventArgs e)    {        MyClass mc = new MyClass();        mc.MyNum = 12;    }

聯繫我們

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