When compiler sees this line, it actually defines a class
public class Add: System.MulticastDelegate {
// Constructor
public Add(Object target, Int32 methodPtr);
// Method with same prototype as specified by the source code
public void virtual Invoke(Int32 a, Int32 b){
// If there are any delegates in the chain that
// should be called first, call them
if (_prev != null) _prev.Invoke(a, b);
// Call our callback method on the specified target object
_target.methodPtr(a, b);
}
// Methods allowing the callback to be called asynchronously
public virtual IAsyncResult BeginInvoke(Int32 a, Int32 b,
AsyncCallback callback, Object object);
public virtual void EndInvoke(IAsyncResult result);
}
2. All delegates are derived from MulticastDelegate.
3. The signature of the Invoke method matches the signature of delegate exactly.
4. In the code below, the constructor Add is taking one parameter but the generated class's constructor has two parameters. Well, compiler magic again
a. The compiler knows that a delegate is being constructed, and the compiler 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.
b. For static methods, null is passed for the target parameter. Inside the constructor, these two parameters are saved in their corresponding private fields.
class Test{
Int32 MyAdd(Int32 a, Int32 b);
static Int32 StMyAdd(Int32 a, Int32 b);
}
Test obj = new Test();
Add a = new Add(obj.MyAdd)
5. There are three private fields that one should be aware of
private IntPtr _methodPtr;
private object _target;
private MulticastDelegate _prev;
6. Adding more than one callback methods
Add obj = null;
obj += new Add(Test.StMyAdd);
obj += new Add(Test.StMyAdd);
You can also use the static Combine methods of the Delegate class.
7. The field _prev allows delegate objects to be part of a linked-list.
8. http://msdn.microsoft.com/en-us/magazine/cc301810.aspx
http://msdn.microsoft.com/en-us/magazine/cc301816.aspx
Uses of delegates
1. Used for implementing callbacks.
2. Used for implementing multicasting.
3. Delegates also provide the primary means for executing a method on a secondary thread in an asynchronous fashion.
No comments:
Post a Comment