在字典中存储代表

Storing Delegates in Dictionary

我正在尝试为代表订阅在 List<KeyValuePair<KeyEnum, Delegate>

中举行的活动

目标是将一系列 Handlers 关联到键盘键和命名轴,这两者都由 Enums 表示

调度相当简单,我只是遍历 KVP 列表,检查一个条件,如果满足条件,只需使用 member.Value; 调用委托我还没有遇到任何效率问题处理器时间,事实上,我们发现它在堆栈上明显更干净。

问题是在实例化后添加到委托中。尝试使用 collection.FirstOrDefault(n=>n.Key == KeyEnum.W).Value+= SomeMethod 访问它是行不通的,因为 Value 是只读的。

有没有一种不需要每次都创建一个新的 KeyValuePair 的方法,或者比 KeyValuePair 一般

更好的解决方案

只需使用一个 Dictionary<KeyEnum, Action>。我不明白为什么您需要顺序访问 KVP。如果可以,您还应该指定与事件处理程序对应的委托类型。 ActionEventHandlerAction<Something> 取决于您的需要。

然后您可以轻松添加和调用代理人:

// adding delegates
if (dictionary.ContainsKey(KeyEnum.W)) {
    dictionary[KeyEnum.W] += SomeMethod;
} else {
    dictionary.Add(KeyEnum.W, SomeMethod);
}

// calling delegates
if (dictionary.ContainsKey(KeyEnum.W)) {
    dictionary[KeyEnum.W](...);
}