C# 如何制作事件词典?

C# 如何制作事件词典?,c#,events,C#,Events,到目前为止,我想要一本事件字典 private Dictionary<T, event Action> dictionaryOfEvents; 私有字典事件; 可以这样做吗?虽然可以有代理字典,但不能有事件字典 private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>(); private Dictionary delegates=new Dic

到目前为止,我想要一本事件字典

private Dictionary<T, event Action> dictionaryOfEvents;
私有字典事件;

可以这样做吗?

虽然可以有代理字典,但不能有事件字典

private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();
private Dictionary delegates=new Dictionary();

其中,
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"); }
private void按钮1\u单击(对象发送者,事件参数e)
{
//声明
Dictionary dictionaryOfEvents=新字典();
//测试数据
Add(“Test1”,delegate(){testMe1();});
Add(“Test2”,delegate(){testMe2();});
Add(“Test3”,delegate(){button2_-Click(button2,null);});
//用法1
foreach(dictionaryOfEvents.Keys中的字符串a)
{Console.Write(“调用“+a+”:”);字典事件[a]();}
//用法2
foreach(dictionaryOfEvents.Values中的操作a)a();
//用法3
字典事件[“test2”]();
}
void testMe1()
void testMe2(){Console.WriteLine(“路上还有一个”);}

事件字典和什么?这是您想要存储的方法或对它们的调用吗?请解释为什么您认为需要事件集合。这将使我们能够帮助您解决问题,而不是回答技术问题。@ernodeweard他可能想取消订阅活动。我会使用一份代表名单。不知道他为什么需要字典。@rezomegreldize-在这种情况下,最好在所有类型上实现IDisposable,并在dispose方法中取消注册。然后,该集合可以只是一个
IList
,但这只是猜测,目前还不是问题的答案。我会这样做,但我会使用一个列表作为字典的值部分,这样我可以在每个键上有多个YourDelegate。@I Hern不需要使用
List
只要
YourDelegate
就足够了,因为它是真的代表可以合并/添加,一旦他们被召集到一起;这也许正是一个人想要的,但也许不是。如果需要自由访问它们,那么可能需要一个列表,甚至第二个,内部字典可能是正确的解决方案。