首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 介面設計:多重繼承、顯式實作與多型應用

     編輯:關於C語言

介面基礎語法

介面定義合約,實作類別或結構必須遵守。可包含方法、屬性、索引子、事件:

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(); // 正確呼叫

優點: 隱藏實作細節、解決同名成員衝突、強制透過介面存取提升封裝性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved