介面:
- 不允許使用存取修飾詞,所有介面成員都是公用的.
- 介面成員不能包含代碼體.
- 介面不能定義欄位成員.
- 介面成員不能使用關鍵字static,vritual,abstract,sealed來定義.
- 類型定義成員是禁止的.
如果要隱藏繼承了介面中的成員,可以用關鍵字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; }