我想要一本事件词典,到目前为止我已经
了private Dictionary<T, event Action> dictionaryOfEvents;
可以做这样的事吗?
答案 0 :(得分:6)
虽然您可以拥有代表字典,但您不能拥有活动字典。
private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();
其中YourDelegate
可以是任何委托类型。
答案 1 :(得分:3)
事件不是类型,但Action是。例如,你可以写:
private void button1_Click(object sender, EventArgs e)
{
// declaration
Dictionary<string, Action> dictionaryOfEvents = new Dictionary<string, Action>();
// test data
dictionaryOfEvents.Add("Test1", delegate() { testMe1(); });
dictionaryOfEvents.Add("Test2", delegate() { testMe2(); });
dictionaryOfEvents.Add("Test3", delegate() { button2_Click(button2, null); });
// usage 1
foreach(string a in dictionaryOfEvents.Keys )
{ Console.Write("Calling " + a + ":"); dictionaryOfEvents[a]();}
// usage 2
foreach(Action a in dictionaryOfEvents.Values) a();
// usage 3
dictionaryOfEvents["test2"]();
}
void testMe1() { Console.WriteLine("One for the Money"); }
void testMe2() { Console.WriteLine("One More for the Road"); }