gpt4 book ai didi

c# - 从函数返回事件

转载 作者:太空狗 更新时间:2023-10-29 22:53:30 25 4
gpt4 key购买 nike

从函数返回事件的语法是什么? (不调用事件,返回它以便它可以绑定(bind)到函数)。

我有一个容器类,其中包含一个字典,其中每个成员都有一个事件。

目标是能够写出这样的东西:

Container c = new Container();
c.CreateEventForKey("a"); // Create the member in the dictionary
c.EventForKey("a") += some_function; // Bind some_function to the event in the "a" member
c.OnEventForKey("a","b"); // Calls some_function with argument "b"

容器类如下所示:

public class Container {

public class Member {
public event Action<string> AnEvent;
public void OnEvent( string v ) { if(AnEvent!=null) { AnEvent(v); } }
}

protected Dictionary<string,Member> members;

// This seems to work OK.
public void OnEventForKey(string k, string v) {
if ( members.ContainsKey(k) ) { members[k].OnEvent(v); }
else { /* report error */ }
}

// Can't get this to compile.
public event Action<string> EventForKey(string k ) {
if ( members.ContainsKey(k) ) { return members[k].AnEvent; }
else { /* report error */ }
}
}

我如何定义 EventForKey 才能达到我的预期?

最佳答案

What is the syntax to return an event from a function?

你不能,很容易。事件 - 就像属性一样 - 并不是真正的一流“对象”;他们是一个类(class)的成员。您在这里实际上没有类成员 - 您只是试图将委托(delegate)保留在字典中。

可以创建您自己的“类事件”容器,但最好考虑其他设计,例如

c.Subscribe("a", SomeFunction);
c.OnEventForKey("a");

您可能想看看 EventHandlerList寻找灵感。

关于c# - 从函数返回事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10257259/

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