我想要一本事件词典,到目前为止我都有
private Dictionary<T, event Action> dictionaryOfEvents;
Run Code Online (Sandbox Code Playgroud)
有可能做这样的事吗?
虽然您可以拥有代表字典,但您不能拥有事件字典.
private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();
Run Code Online (Sandbox Code Playgroud)
哪里YourDelegate可以是任何委托类型.
事件不是类型,但动作是。例如你可以这样写:
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"); }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3825 次 |
| 最近记录: |