Question

I am building a game project using C# .NET 3.5, and have mistyped a couple of the event subscriptions, but the resulting code still compiles and acts very strangely.

Normally when you subscribe to a C# event, you would declare the type of event handler (a delegate) and the name of the function that will actually handle the event, as follows:

myObject.StateChanged += new EventHandler(ObjectStateChanged);

private void ObjectStateChanged(object sender, EventArgs e) {
    // handle event here...
    }

What I've written in a few places is this:

MyObject.StateChanged += ObjectStateChanged;

So it subscribes to the event without explicitly declaring the event handler type. This produces all kinds of strange behaviour, mostly duplicate calls (in one playtest the event handler was called 4 times when the event was fired once). The code compiles though, and when replacing += ObjectStateChanged with += new EventHandler(ObjectStateChanged), it runs normally.

So, my question is: in this circumstance, is the behaviour well-defined, and what should the code actually do?

Était-ce utile?

La solution

First of all

myObject.StateChanged += new EventHandler(ObjectStateChanged);

is equivalent to

myObject.StateChanged += ObjectStateChanged;.

It's just a shorthand version of first syntax.

Second, handler is called multiple times since you might have hooked a delegate multiple time using +=.

So, what you should do is prior of hooking a delegate, make sure you first unhook in case already hooked:

myObject.StateChanged -= ObjectStateChanged;
myObject.StateChanged += ObjectStateChanged;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top