asp.net.ph

Delegate Class

System Namespace


Represents a delegate, which is a data structure that refers to a static method or to an object instance and an instance method of that object.

Delegate Class Members

Collapse   Properties

Visibility Name Value Type Accessibility
public Method MethodInfo [ Get ]
public Target Object [ Get ]

Collapse   Methods

Visibility Name Parameters Return Type
public Clone ( ) Object
public static Combine ( Delegate a , Delegate b ) Delegate
public static Combine ( Delegate delegates ) Delegate
protected CombineImpl ( Delegate d ) Delegate
public static CreateDelegate ( Type type , Type target , String method ) Delegate
public static CreateDelegate ( Type type , Object target , String method , Boolean ignoreCase , Boolean throwOnBindFailure ) Delegate
public static CreateDelegate ( Type type , Object target , String method , Boolean ignoreCase ) Delegate
public static CreateDelegate ( Type type , Object target , String method ) Delegate
public static CreateDelegate ( Type type , Object firstArgument , MethodInfo method ) Delegate
public static CreateDelegate ( Type type , Object firstArgument , MethodInfo method , Boolean throwOnBindFailure ) Delegate
public static CreateDelegate ( Type type , MethodInfo method ) Delegate
public static CreateDelegate ( Type type , Type target , String method , Boolean ignoreCase ) Delegate
public static CreateDelegate ( Type type , Type target , String method , Boolean ignoreCase , Boolean throwOnBindFailure ) Delegate
public static CreateDelegate ( Type type , MethodInfo method , Boolean throwOnBindFailure ) Delegate
public DynamicInvoke ( Object args ) Object
protected DynamicInvokeImpl ( Object args ) Object
public Equals ( Object obj ) Boolean
public GetHashCode ( ) Int32
public GetInvocationList ( ) Delegate
protected GetMethodImpl ( ) MethodInfo
public GetObjectData ( SerializationInfo info , StreamingContext context ) Void
public static Remove ( Delegate source , Delegate value ) Delegate
public static RemoveAll ( Delegate source , Delegate value ) Delegate
protected RemoveImpl ( Delegate d ) Delegate

Remarks

The Delegate class is the base class for delegates.

The closest equivalent of a delegate in C or C++ is a function pointer. However, a function pointer can only reference static functions, whereas a delegate can reference both static and instance methods. When the delegate references instance methods, the delegate stores not only a reference to the method's entry point, but also a reference to the object instance for which to invoke the method. Unlike function pointers, delegates are object-oriented, type-safe and secure.

An invocation list is a linked list of delegates that are to be invoked when the Invoke method is called.

A delegate that inherits directly from the Delegate class has an invocation list with only one element -- itself. A delegate that inherits from the MulticastDelegate class may have an invocation list with more than one element. The Combine and Remove methods are used to create new invocation lists.

Derived classes of Delegate and MulticastDelegate are declared with special syntax.

For example, the following declarations are for a delegate that encapsulates a method that takes a single parameter of type String and has no return value:

// Managed C++ delegate declaration
 __delegate void mySingleCast ( String *value );

[ VB ]
' VB delegate declaration
Public Delegate Sub mySingleCast ( value As String )
    

When these declarations are compiled, a class by the name of mySingleCast is generated. This class has two members, a constructor and an Invoke method. The compiler generates metadata for these members and sets a bit indicating that no implementation is provided. The EE provides the implementation. Although the class declarations that follow are not 100% accurate, they offer a glimpse of what the declaration for mySingleCast would look like if the compiler did not generate the class from the simplified delegate declaration syntax given above.

// Managed C++ pseudo code For mySingleCast
    Class mySingleCast {
        Public :
        mySingleCast ( Object * obj, int ptr );
        Public :
        void Invoke ( String * value );
        };

[ VB ]
' VB pseudo code for mySingleCast
Class mySingleCast
    Public Sub New ( obj As Object, ptr As Long )
        Public Sub Invoke ( value As String )
        End Class
        

Observe that the mySingleCast class contains two members ( this is true for every derived class of Delegate and MulticastDelegate ). The first member is a constructor with the metadata signature .ctor ( System/Object, I4 ), where .ctor indicates that the member is a constructor, System/Object indicates the first parameter is an Object and I4 indicates that the second parameter is a 4-byte integer. The first parameter is the target of the delegate and the second parameter is the address of the method body. The second member of a mySingleCast is a method with the metadata signature Void Invoke ( System/String ). The parameter list, which consists a single String parameter, indicates that the mySingleCast delegate encapsulates methods that take a single String parameter. Note that the Invoke method is used for early bound invocation of the method encapsulated by this delegate ( late bound invocation is accomplished via Delegate.DynamicInvoke ).

Compilers are free to access the constructor in any way they choose; this constructor requires special handling. For example, observe the difference in how the mySingleCast constructor is invoked in Managed C++ and VB:

// Managed C++ Delegate instantiation
Class myEcho {
    Public :
    void shout ( String * value ) { Console : : WriteLine ( value ); };
    };

    void main ( ) {
    myEcho * obj = New myEcho ( );
    mySingleCast * dlgt = New mySingleCast ( obj, & myEcho : : shout );
    // alternative : mySingleCast * dlgt = New mySingleCast ( obj -> shout );
    dlgt -> Invoke ( "Argh!" );
    };

[ VB ]
' VB pseudo code for mySingleCast
Class myEcho
    Public Sub Shout ( value As String )
        Response.Write ( value )
    End Sub
End Class
Sub main
    Dim obj As myEcho
    Set obj = New myEcho ( )
    Dim dlgt As mySingleCast
    Set dlgt = New mySingleCast ( AddressOf obj.shout )
    dlgt.Invoke ( "Argh!" )
End Sub

Observe that VB invokes the mySingleCast constructor with an expression as the parameter ( AddressOf obj.shout ). This is due to the fact that VB does not allow the address of a method to be determined in any other way. The Microsoft intermediate language that is emitted by the VB compiler actually calls the constructor discussed above, passing an Object reference and the address of the method body. In contrast, Managed C++ allows the mySingleCast constructor to be invoked directly--new mySingleCast ( obj, &myEcho::shout ). Alternatively, the following syntax may be used: new mySingleCast ( obj->shout ). ( Note that even if the method to be encapsulated is static, Managed C++ does not allow the constructor of a delegate to be invoked with only the address of a member of a managed class. Managed C++ may choose to do this in the future, since the constructor for every derived class of Delegate or MulticastDelegate allows the target object to be a null reference if the method is static. )

Compilers provide two additional methods to the Delegate instance: BeginInvoke ( ) and EndInvoke ( ). For more information on these methods, see Asynchronous Programming Model Implementation Notes.

Example

The following example shows how to define a standard delegate.

[ VB ]
Imports System
Imports Microsoft.VisualBasic

Public Class SamplesDelegate

    ' Declare a delegate for a method that takes in an int and returns a String.
    Delegate Function myMethodDelegate ( myInt As Integer ) As String

    ' This subclass defines some methods that the delegate can point to.
    Public Class mySubClass

        Public Shared Function myStringMethod ( myInt As Integer ) As String
            If myInt > 0 Then
                Return "positive"
            End If
            If myInt < 0 Then
                Return "negative"
            End If
            Return "zero"
        End Function

        Public Shared Function mySignMethod ( myInt As Integer ) As String
            If myInt > 0 Then
                Return ChrW ( 43 )
            End If
            If myInt < 0 Then
                Return "-"
            End If
            Return ""
        End Function
    End Class

    Public Shared Sub Main ( )

        ' create one delegate for each method.
        Dim myD1 As New myMethodDelegate ( AddressOf mySubClass.myStringMethod )
        Dim myD2 As New myMethodDelegate ( AddressOf mySubClass.mySignMethod )

        ' Invoke the delegates.
        Response.Write ( "{0} is {1}; use the sign ""{2}""." _
           + ControlChars.Cr, 5, myD1 ( 5 ), myD2 ( 5 ) )
        Response.Write ( "{0} is {1}; use the sign ""{2}""." _
           + ControlChars.Cr, - 3, myD1 ( - 3 ), myD2 ( - 3 ) )
        Response.Write ( "{0} is {1}; use the sign ""{2}""." _
           + ControlChars.Cr, 0, myD1 ( 0 ), myD2 ( 0 ) )
    End Sub
End Class

' Output:
'
' 5 is positive; use the sign "+".
' -3 is negative; use the sign "-".
' 0 is zero; use the sign "".

[ C# ]
using System;
public class SamplesDelegate  {

   // Declare a delegate for a method that takes in an int and returns a String.
   public delegate String myMethodDelegate ( int myInt );

   // This subclass defines some methods that the delegate can point to.
   public class mySubClass  {

      public static String myStringMethod ( int myInt ) {
         if ( myInt > 0 )
            return ( "positive" );
         if ( myInt < 0 )
            return ( "negative" );
         return ( "zero" );
      }

      public static String mySignMethod ( int myInt ) {
         if ( myInt > 0 )
            return ( "+" );
         if ( myInt < 0 )
            return ( "-" );
         return ( "" );
      }
   }

   public static void Main ( ) {

      // create one delegate for each method.
      myMethodDelegate myD1 = new myMethodDelegate ( mySubClass.myStringMethod );
      myMethodDelegate myD2 = new myMethodDelegate ( mySubClass.mySignMethod );

      // Invoke the delegates.
      Response.Write ( "{0} is {1}; use the sign \"{2}\".\n", 5, myD1 ( 5 ), myD2 ( 5 ) );
      Response.Write ( "{0} is {1}; use the sign \"{2}\".\n", -3, myD1 ( -3 ), myD2 ( -3 ) );
      Response.Write ( "{0} is {1}; use the sign \"{2}\".\n", 0, myD1 ( 0 ), myD2 ( 0 ) );
   }

}
/*
Output:

5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
 */
See Also

MulticastDelegate Skip Navigation Links




Home
Suggested Reading


Previous page Back to top Next page

© 2000-2010 Rey Nuñez All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note

You can help support asp.net.ph