我希望拥有一个事件字典,目前我已经有:
private Dictionary<T, event Action> dictionaryOfEvents;
能否做到这样的事情呢?
虽然你不能拥有事件的字典,但你可以拥有委托的字典。
private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();
这里的YourDelegate
可以是任何委托类型。
Event不是类型,但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"); }
你不能直接定义一个事件类型的字典,但是你可以在类内部定义该事件。
private Dictionary<string, MyEventManager> dictionaryOfEvents;
dictionaryOfEvents["key1"].CallMyEvent();
MyEventManager类的示例实现:
public class MyEventManager {
public event Action MyEvent;
public void CallMyEvent => MyEvent.Invoke()
}
IList<IDisposable>
。 但这只是猜测,目前还不是问题的答案。 - Emond