从函数返回事件的语法是什么? (不调用事件,返回它以便它可以绑定(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/