A delegate is a reference type that can be passed through a method or included in the parameter list of a method, just like any other reference type.
Here is an example:
In this example, we will use a delegate to write a method for a common class library. Computeit () Evaluate the expression of the functions V and T. The first part of the expression is the V function. All values of T are the same. The second part of the expression is the T function, which has different evaluate values based on the T value. For the low value of T, it should be evaluated in one way, and for the high value of T, it should be evaluated in another way.
One way to deal with this situation is to use the delegate definition. Computeit () Different versions, A low value of computing t , A high value of computing t . A more compact approach is to use a delegate to define a general version that can be used in various situations.
The computeit () method has three parameters: two dual-Precision values corresponding to the V and T parameters, and the reference and delegate-related methods of a delegated instance are used to calculate the second part related to the expression and the tvalue. Public Static Double Computeit ( Double V, Double T, equation eq)
{< br> return ( 0.5 * v * V) + eq (t );
}
The equation delegate is defined to include a double parameter and return a sub-double value.Public Delegate DoubleEquation (DoubleX );
The following code calls the delegate Code :
The first delegate is associated with the lowt () method. The second delegate is associated with the hight () method. In both cases, the syntax for calling the computeit () method is the same, but the output results of the method are different, because different methods are called within the method. Public Delegate Double Equation ( Double X );
Class Class1
{
/**/ /// <Summary>
///ApplicationProgram.
/// </Summary>
[Stathread]
Static Void Main ( String [] ARGs)
{
//
// Todo: Add code here to start the application
//
Double Result;
Equation eqn;
// First delegated instance
Eqn = New Equation (class1.lowt );
Result = Class1.computeit ( 100.0 , 4000.0 , Eqn );
Console. writeline ( " Result is {0} " , Result );
Eqn = New Equation (class1.hight );
Result = Class1.computeit ( 100.0 , 4000.0 , Eqn );
Console. writeline ( " Result is {0} " , Result );
Console. Readline ();
}
// Two methods
Public Static Double Lowt ( Double T)
{
Return 1009.0*T;
}
Public Static Double Hight ( Double T)
{
Return(1009.0*T)+(0.1*T*T );
}
Public Static Double Computeit ( Double V, Double T, equation eq)
{
Return(0.5*V*V)+Eq (t );
}
}