每個事件可訂閱多個處理器,依序呼叫。若某處理器拋出例外,後續處理器將不再執行。建議事件處理器:
// 訂閱事件
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; }
}
}