gpt4 book ai didi

C# 事件 - 根据字符串引发特定事件

转载 作者:行者123 更新时间:2023-11-30 16:07:41 24 4
gpt4 key购买 nike

我正在编写一个类来处理来自具有字符串值的单个事件的事件,并将它们映射到并根据字符串值引发特定事件。

这一切都可以通过诸如 switch 之类的开关正常工作

SpecificHandler handler = null;
SpecificArgs args = new SpecificArgs(Id, Name);
switch (IncomingEventName)
{
case "EVENT1":
handler = Event1Handler;
break;
case "EVENT2":
handler = Event2Handler;
break;
... etc
}
if (handler != null) handler(this, args);

但是开关列表可能会变得太长,所以我想要一种方法,将字符串事件映射到数据结构中的处理程序(例如 KeyValuePair 列表),这样我就可以找到字符串事件的项目并引发相关事件。

欢迎任何提示/想法。

谢谢

最佳答案

你可以只使用字典。但是,请注意不要针对委托(delegate),而是对它们进行惰性评估。因此,委托(delegate)是不可变的,因此您不会收到任何事件处理程序,否则。

private static Dictionary<string, Func<Yourtype, SpecificHandler>> dict = ...
dict.Add("Foo", x => x.FooHappened);
dict.Add("Bar", x => x.BarHappened);

并像这样使用它:

Func<SpecificHandler> handlerFunc;
SpecificArgs args = new SpecificArgs(...);
if (dict.TryGetValue(IncomingEventName, out handlerFunc))
{
SpecificHandler handler = handlerFunc(this);
if (handler != null) handler(this, args);
}

关于C# 事件 - 根据字符串引发特定事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com