2014-07-20 31 views
0

我想有事件的字典,到目前为止,我如何制作事件字典?

private Dictionary<T, event Action> dictionaryOfEvents; 

是有可能做这样的事情?

+1

字典的事件和什么? –

+0

那是你想要存储的方法还是对它们的调用? – TaW

+0

请解释你为什么认为你需要一系列活动。这将使我们能够帮助您解决问题,而不是回答技术问题。 –

回答

6

尽管您可以拥有代表字典,但您不能拥有活动字典。

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

其中YourDelegate可以是任何委托类型。

+0

我会这样做,但我会使用List 作为字典的值部分,以便每个键可以有多个YourDelegates。 –

+3

@IanHern无需使用'List '只需'YourDelegate'就足够了[代表可以合并](http://msdn.microsoft.com/en-IN/library/ms173175.aspx) –

+0

虽然它是确实可以组合/添加代表,一旦他们被召集在一起;这可能正是人们想要的,但也许并非如此。如果想要自由地访问它们,那么可能是一个List或甚至第二个内部字典可能是正确的解决方案。 – TaW

2

事件不是一个类型,但行动是。因此,例如你可以写:

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"); }