[英]Create Dictionary for delegates and events
I want to create a dictionary like this: 我想创建一个这样的字典:
public class MyClass
{
public delegate void CreateClickEvent(string value);
public event CreateClickEvent OnCreateClick;
public delegate void CreateHoverEvent(string value);
public event CreateHoverEvent OnCreateHover;
private Dictionary<string,Delegate> _myDictionary = null;
public MyClass()
{
_myDictionary = new Dictionary<string,Delegate>();
_myDictionary.Add("Click", OnCreateClick);
_myDictionary.Add("Hover", OnCreateHover);
}
public void Call(string name)
{
Delegate action;
if (_myDictionary.TryGetValue(name, out action))
{
if (action != null)
action.DynamicInvoke( "something" );
else
Console.WriteLine("null");
}
else
Console.WriteLine("Couldn't find action");
}
}
public class Tester()
{
public Tester()
{
MyClass MyClass = new MyClass();
myClass.OnCreateClick += RaiseCreateClickEvent;
myClass.OnCreateHover += RaiseCreateHoverEvent;
}
public void RaiseCreateClickEvent(string value)
{
///do it here
}
public void RaiseCreateHoverEvent(string value)
{
///do it here
}
}
but unfortunately, the method RaiseCreateClickEvent or RaiseCreateHoverEvent (class Tester) is not calling from Call method (class MyClass). 但不幸的是,方法RaiseCreateClickEvent或RaiseCreateHoverEvent (类Tester)不是从Call方法(类MyClass) 调用 。 And it's not giving any error and action variable is looking null and printing null . 并且它没有给出任何错误,并且操作变量看起来为null并且打印为null 。
What am I doing wrong here? 我在这做错了什么?
You have dictionary of delegates, but it keeps values of your events at the moment of creation of the dictionary. 您有代理字典,但它在创建字典时保留事件的值 。 At that point both OnCreateXXXX
are null
. 此时, OnCreateXXXX
都为null
。
As an option can use dictionary of Action
and call event in each so action will use current value of the event, not the initial one: 作为一个选项,可以在每个操作中使用Action
字典和调用事件,因此操作将使用事件的当前值,而不是初始值:
private Dictionary<string,Action<string>> _myDictionary =
new Dictionary<string,Action<string>>();
_myDictionary.Add("Click", s => OnCreateClick(s));
_myDictionary.Add("Hover", s => OnCreateHover(s));
And use: 并使用:
_myDictionary["Click"] ("sometext");
Note good reading on delegates (and especially how +
/ +=
impacts value) is available http://csharpindepth.com/Articles/Chapter2/Events.aspx 请注意代表们的良好阅读(特别是如何+
/ +=
影响价值)可用http://csharpindepth.com/Articles/Chapter2/Events.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.