"Douglas Peterson" <Tergiver@nospam.msn.com> schrieb im Newsbeitrag
news:%23tb$hFZ7GHA.1188@TK2MSFTNGP05.phx.gbl...
[quoted text, click to view] >I created the following code:
>
> private struct StackItem
> {
> public EventHandler theEvent, theHandler;
> public StackItem(EventHandler theEvent, EventHandler theHandler)
> {
> this.theEvent = theEvent;
> this.theHandler = theHandler;
> }
> }
>
> protected void AddHandler(EventHandler theEvent, EventHandler theHandler)
> {
> theEvent += theHandler; // add handler to event
> stack.Push(new StackItem(theEvent, theHandler)); // note the fact that we
> did so
> }
>
> public virtual void Dispose()
> {
> while (stack.Count > 0)
> {
> StackItem si = (StackItem)stack.Pop();
> si.theEvent -= si.theHandler; // remove the handler from the event
> }
> }
>
> So that my derived classes can register for various events of various
> controls on my form without having to make certain to add both the
> subscribe and unsubscribe lines of code. However, the following code:
>
> AddHandler(form.listView.SizeChanged, new
> System.EventHandler(this.listView_SizeChanged));
>
> gives the following error:
>
> "The event 'System.Windows.Forms.Control.SizeChanged' can only appear on
> the left hand side of += or -="
>
> I assume this is some attribute of the SizeChanged member of the various
> stock controls. Is there any way around this?
The cause is, that SizeChanged is an event and not a delegate field or
property.
Events can only be used on the left side of += or -= operators.
(An exception are field like events wich inside!! the class where they are
defined behave like fields of a delegate type.) Even if SizeChanged was a
field or property of a delegate type your code wouldn't work, because
delegates are imutable, and the operations would create only new delegate
instances wich will be stored in your stack item, but not in the Control.
[quoted text, click to view] >
> Why do I need to unsubscribe? Because I'm using objects to implement
> various states in my application. When the app changes states it needs to
> unhook the current state object from all events so that the new state can
> take over.
>
possible solutions:
1. for every Event make a static method, wich is subscribed once and calls
the appropriate handler on the actual stateobject.
2. make two methods wich do all the subscribing and unsubscribing of the
event.
3. store the old state object, and for every event make a method or
codeblock wich does the subscribing and the unsubscribing:
if (olsState != null)
control.Event -= oldState.Handler();
control.Event += newState.Handler();
4. in the StackItem store the MemberInfo of the event.