创建自定义事件字典






1.70/5 (9投票s)
一篇关于创建自定义事件字典的文章。
引言
这个集合允许开发者从中心化的来源调用任意数量的事件。
使用代码
只需像实例化常规的 Dictionary
类一样实例化 EventDictionary
类,并使用 EventDictionary.Add
方法传入一个 EventHandler
。
using System;
using System.Collections.Generic;
/// <summary>
/// Represents a collection of key/event pairs that are accessible by the
/// event name.
/// </summary>
public class EventDictionary : Dictionary<string, EventHandler>
{
...
/// <summary>
/// Adds an entry with the specified value into the EventDictionary
/// collection with the EventHandler's name as the key.
/// </summary>
/// <param name="e">The value of the event to add. This value cannot
/// be null (Nothing in Visual Basic).</param>
public void Add(EventHandler e)
{
if (e == null)
throw new ArgumentException("Event Handler cannot be null.",
"e");
string s = e.Target.GetType().GetEvents()[0].ToString();
base.Add(s.Substring(s.LastIndexOf(" ") + 1), e);
}
}