Best way to wire events to an object?
I have a class which has a member object (class variable). This object has some events. I'd like to expose these events directly in my class.开发者_运维技巧 What is the best way to do this?
If you want to expose the events directly (without defining new handlers that you would forward to your subscribers) you could do this:
class MyClass {
private readonly OtherClass other = new OtherClass();
public event EventHandler Click {
add { other.Click += value; }
remove { other.Click -= value; }
}
}
The advantage to this method is that you don't need to handle the events from OtherClass and forward them as your own. The disadvantage (and the reason I declared the "other" field as readonly) is that anyone who hooks up to MyClass's Click event is really hooking up to OtherClass's Click event indirectly. So you wouldn't want to just change out the other instance because subscribers that were already handling the event wouldn't be called.
精彩评论