Delegate delegate is a special class with only one function
Delegate object reference equivalent function pointer
The delegate Declaration defines a reference type that can be used to encapsulate a method with a specific signature. The delegated instance encapsulates static methods or instance methods. The delegate is similar to the function pointer in C ++. However, the delegate type is safe and reliable.
Delegate allows you to pass functions as parameters. Delegate type security requirements the function passed as a delegate has the same signature as the delegate Declaration
Delegate allows programmers to encapsulate method references in the delegate object. You can then pass the delegate object to a method without knowing which method will be called during compilation. Unlike function pointers in C or C ++, delegation is object-oriented and type-safe.
A delegate Declaration defines a type, which uses a specific set of parameters and the return type encapsulation method. For static methods, the delegate object encapsulates the methods to be called. For instance methods, the delegate object encapsulates an instance and a method on the instance at the same time. If you have a delegate object and a set of appropriate parameters, you can use these parameters to call the delegate.
An interesting and useful attribute of delegation is the class of the object that it does not know or care about. All objects are allowed. Only the parameter type and return type of the method must match the parameter type and return type of the delegate. This makes the delegate fully suitable for "anonymous" calls.
Class Program
{
Delegate bool compareop (INT V1, int V2 );
Static void main (string [] ARGs)
{
Compareop less = new compareop (program. Less );
Console. writeline (less (1, 2). tostring ());
Console. writeline ("test delegate ");
Console. Readline ();
}
Static public bool less (int A, int B)
{
Return a <B;
}
}
// 2
Delegate void mydelegate (int I );
Class Program
{
Public static void main ()
{
Takesadelegate (New mydelegate (delegatefunction ));
}
Public static void takesadelegate (mydelegate somefunction)
{
Somefunction (21 );
}
Public static void delegatefunction (int I)
{
System. Console. writeline ("called by Delegate with number: {0}.", I );
}
}