介面定義合約,實作類別或結構必須遵守。可包含方法、屬性、索引子、事件:
interface IExample {
string this[int index] { get; set; }
event EventHandler E;
void F(int value);
string P { get; set; }
}
public delegate void EventHandler(object sender, EventArgs e);
介面可繼承多個基底介面,形成菱形繼承結構:
interface IControl { void Paint(); }
interface ITextBox : IControl { void SetText(string text); }
interface IListBox : IControl { void SetItems(string[] items); }
interface IComboBox : ITextBox, IListBox {} // 同時繼承兩者
interface IDataBound { void Bind(Binder b); }
public class EditBox : Control, IControl, IDataBound {
public void Paint() { ... }
public void Bind(Binder b) { ... }
}
避免公開介面成員,使用限定名稱實作:
public class EditBox : IControl, IDataBound {
void IControl.Paint() { ... } // 僅能透過 IControl 呼叫
void IDataBound.Bind(Binder b) { ... }
}
// 使用方式
EditBox editbox = new EditBox();
// editbox.Paint(); // 編譯錯誤
IControl control = editbox;
control.Paint(); // 正確呼叫
優點: 隱藏實作細節、解決同名成員衝突、強制透過介面存取提升封裝性。