asp net 3.5unleashed

Page 334

Notice that all delegates have a constructor that takes two parameters: a reference to an object and an integer that refers to the callback method. However, if you examine the source code, you’ll see that I’m passing in values such as App.FeedbackToConsole or appobj.FeedbackToFile. All your sensibilities tell you that this code shouldn’t compile! However, the compiler knows that a delegate is being constructed and parses the source code to determine which object and method are being referred to. A reference to the object is passed for the target parameter, and a special Int32 value (obtained from a MethodDef or MethodRef metadata token) that identifies the method is passed for the methodPtr parameter. For static methods, null is passed for the target parameter. Inside the constructor, these two parameters are saved in their corresponding private fields. In addition, the constructor sets the _prev field to null. This _prev field is used to create a linked list of MulticastDelegate objects. I’ll ignore this field for now but cover it in detail later in the chapter, in the section "Delegate Chains." So, each delegate object is really a wrapper around a method and an object to be operated on when the method is called. The MulticastDelegate class defines two read-only public instance properties: Target and Method. Given a reference to a delegate object, you can query these properties. The Target property returns a reference to the object that will be operated on if the method is called back. If the method is a static method, Target returns null. The Method property returns a System.Reflection.MethodInfo object that identifies the callback method. You could use this information in several ways. For example, you could check to see whether a delegate object refers to an instance method of a specific type: Boolean DelegateRefersToInstanceMethodOfType( MulticastDelegate d, Type type) {

return((d.Target != null) && d.Target.GetType() == type); } You could also write code to check whether the callback method has a specific name (such as FeedbackToMsgBox): Boolean DelegateRefersToMethodOfName( MulticastDelegate d, String methodName) {

return(d.Method.Name == methodName); } Now that you know how delegate objects are constructed, let’s talk about how the callback method is invoked. For convenience, I’ve repeated the code to Set’s ProcessItems here: public void ProcessItems(Feedback feedback) { for (Int32 item = 0; item < items.Length; item++) { if (feedback != null) { // If any callbacks are specified, call them. feedback(items[item], item, items.Length); }


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