开发者

Remove events without knowing their names

Is it possible to instead of doing this:

person.Walking -= person_Walking1;
person.Walking -= person_Walking2;
person.Walking -开发者_开发问答= person_Walking3;

Do this:

person.Walking = // remove all the handlers without knowing their names

Thanks.


No. Part of the point of events is that they prevent you from doing that. If I've subscribed to a button click and you've subscribed to a button click, what right have you to remove my handler? (Okay, that's anthropomorphising somewhat, but you get the idea.) Note that it's not a matter of knowing the "name" of an event handler - you have to be able to provide a reference to an "equal" delegate instance.

For example, if you subscribe to an event using an anonymous method or a lambda expression, you'll have to keep a reference to that somewhere:

EventHandler handler = (sender, args) => Console.WriteLine("Clicked!");
button.Click += handler;
...
button.Click -= handler;

When you use the name of a method, that's performing a method group conversion from the name of the method to a delegate instance:

button.Click += HandleEvent;
...
button.Click -= HandleEvent;

Here there are two separate delegate instances involved, but they're equal as they have the same invocation list (they do the same thing) and they have the same target (they're doing that thing "on" the same object).

EDIT: I'm assuming you only have access to it as an event, not as a field - if you're writing code in the class which publishes the event, you can do what you like, and setting the field to null (or removing it from the collection, or however your implementation works) is fine.


Sure. Just set:

person.Walking = null;


This is one of the reasons events were invented. If you wanted to do something like that, use delegates.


Not from outside the class in which the events are defined. If you really wanted to, you could define a method like this:

public void ClearEventListeners() {
    MyEvent.Clear();
}

(The exact call may be different, if it exists, but IntelliSense should point you in the right direction.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜