asp net 3.5unleashed

Page 341

When the head of the delegate chain is invoked, it calls any previous delegate in the chain. However, notice that the previous delegate’s return value is discarded. Your application code will receive the return value only from the delegate that is at the head of the chain (the last callback method called). Note Once constructed, delegate objects are considered to be immutable; that is, delegate objects always have their _prev fields set to null and this never changes. When you Combine a delegate object to a chain, internally, Combine constructs a new delegate object that has the same _target and _methodPtr fields as the source object but the _prev field is set to the old head of the chain. The address of the new delegate object is returned from Combine. This behavior is demonstrated in the following lines of code: Feedback fb = new Feedback(FeedbackToConsole); Feedback fbChain = (Feedback) Delegate.Combine(fb, fb); // fbChain refers to a chain of two delegate objects. // One of the objects is identical to the object referred // to by fb. The other object was constructed by Combine. // This object’s _prev field refers to fb, and Combine // returns the reference to this new object.

// Do fb and fbChain refer to the same object? "False" Console.WriteLine(Object.ReferenceEquals(fb, fbChain);

// Do fb and fbChain refer to the same callback // target/method? "True" Console.WriteLine(fb.Equals(fbChain)); Now that you know how to build delegate chains, let’s look at how to remove a delegate from a chain. To remove a delegate from a linked list, you call the Delegate type’s static Remove method: Feedback fb1 = new Feedback(FeedbackToConsole); Feedback fb2 = new Feedback(FeedbackToMsgBox); Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2); // fbChain refers to a chain of two delegates.

// Invoke the chain: two methods are called. if (fbChain != null) fbChain(null, 0, 10);

fbChain = (Feedback) Delegate.Remove(fbChain, new Feedback(FeedbackToMsgBox)); // fbChain refers to a chain with one delegate.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.