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

C# 事件與索引器深度解析

     編輯:關於C語言

事件多播與異常處理

每個事件可訂閱多個處理器,依序呼叫。若某處理器拋出例外,後續處理器將不再執行。建議事件處理器:

  • 快速完成處理邏輯
  • 內部捕獲異常,避免中斷事件鏈
  • 避免長時間阻塞操作

事件訂閱與取消訂閱

// 訂閱事件
public void Subscribe(EventSender sender)
{
    TestEventDelegate handler = new TestEventDelegate(ReceiveTestEvent);
    sender.TestEvent += handler;
}

// 取消訂閱
public void Unsubscribe(EventSender sender)
{
    TestEventDelegate handler = new TestEventDelegate(ReceiveTestEvent);
    sender.TestEvent -= handler;
}

注意:取消訂閱時需使用相同的委派實例,建議將委派儲存為欄位。

索引器語法與特性

索引器讓類別實例支援陣列式存取語法:

public class SampleCollection<T>
{
    private T[] arr = new T[100];

    public T this[int index]
    {
        get { return arr[index]; }
        set { arr[index] = value; }
    }
}

索引器關鍵特性

  • 使用 this 關鍵字宣告
  • 支援多載(不同參數型別/數量)
  • 可使用 string 等非整數型別當索引
  • 修飾詞:public、virtual、override 等
  • 不可作為 ref/out 參數傳遞

實際應用範例

class Program
{
    static void Main()
    {
        var collection = new SampleCollection<string>();
        collection[0] = "索引器的使用";
        Console.WriteLine(collection[0]);
    }
}

字串索引器實作

public class StringIndexedCollection
{
    private Dictionary<string, object> _data = new Dictionary<string, object>();

    public object this[string key]
    {
        get { return _data.ContainsKey(key) ? _data[key] : null; }
        set { _data[key] = value; }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved