Reputation: 159
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). And it's not giving any error and action variable is looking null and printing null.
What am I doing wrong here?
Upvotes: 1
Views: 2984
Reputation: 100547
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
.
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:
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
Upvotes: 3