I want to share with you how to use C # delegation today:
A delegate is a data structure that references static methods, class instances, and class instance methods. Let's take a look at the following example:
Int I = 100; // defines the number of integers.
Public Delegate string getstring (); // defines a delegate getstring, which returns the string type.
Getstring firstmethod = new getstring (I. tostring); // a delegate whose instantiation type is getstring.
Let's not talk about it. Let's look at an example. It's a simple example that everyone can understand:
View code
Using System;
Using System. Collections. Generic;
Using System. text;
Namespace Wrox. procsharp. Delegates
{
Class Mathoperations
{
Public Static Double Multiplybytwo ( Double Value)
{
Return Value * 2 ;
}
Public Static Double Square ( Double Value)
{
Return Value * Value;
}
}
Delegate Double Doubleop ( Double X );
Class Mainentrypoint
{
Static Void Main ()
{
Doubleop [] operations =
{
Mathoperations. multiplybytwo,
Mathoperations. Square
// New doubleop (mathoperations. multiplybytwo ),
// New doubleop (mathoperations. Square)
};
For ( Int I = 0 ; I < Operations. length; I ++ )
{
Console. writeline ( " Using operations [{0}]: " , I );
Processanddisplaynumber (Operations [I], 2.0 );
Processanddisplaynumber (Operations [I], 7.94 );
Processanddisplaynumber (Operations [I], 1.414 );
Console. writeline ();
}
Console. Readline ();
}
Static Void Processanddisplaynumber (doubleop action, Double Value)
{
Double Result = Action (value );
Console. writeline (
" Value is {0}, result of operation is {1} " , Value, result );
}
}
}
A good way to understand the delegate is to treat the delegate as a name for the method signature and return type.
Processanddisplaynumber (Operations [I], 2.0); // indicates passing the delegate to the processanddisplaynumber () method.
I will write it here today. For more information about the many shortcomings, please consult.