如何制作活动词典?

Ian*_*ern 3 c# events

我想要一本事件词典,到目前为止我都有

private Dictionary<T, event Action> dictionaryOfEvents;
Run Code Online (Sandbox Code Playgroud)

有可能做这样的事吗?

Sri*_*vel 7

虽然您可以拥有代表字典,但您不能拥有事件字典.

private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();
Run Code Online (Sandbox Code Playgroud)

哪里YourDelegate可以是任何委托类型.

  • @IanHern不需要使用`List <YourDelegate>`只是`YourDelegate`就够了[委托可以合并](http://msdn.microsoft.com/en-IN/library/ms173175.aspx) (4认同)

TaW*_*TaW 5

事件不是类型,但动作是。例如你可以这样写:

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)