I understand the delegate as: the delegate is the format of a method, and of course he is a type.
as long as the format of the method is the same as the format of the delegate definition, you can attach the method to the delegate. See Demo below
Declaring a delegate:
<p style= "margin:0in;font-family: Microsoft Jas Black; font-size:12.0pt" ></p><pre name= "code" class= "CSharp" > public delegate void Add (int a,int b);
Declare a method of the same format:
static void Othermethod (int a, int b) { Console.WriteLine (a+b); }
Declaring a member variable of a delegate type to a class
public class person {public string Name {set; get;} public string Age {set; get;} Public Add myadd; }
Attach the method to the delegate, call it, and test the following:
Static Voidmain (string[] args) {person P1 =new person (); P1. Myadd = Othermethod; P1. Myadd (7, 8); Console.ReadLine ();}
Console output-- the
If we define the Othermethod infrequently, there is no need to declare a method separately. You can use anonymous methods, that is, when attaching a method to a delegate, it is possible to construct an anonymous method that is identical to the delegate format:
The wording is as follows:
P1. Myadd = Delegate (inta, int b) {Console.WriteLine (A + b);};
Anonymous methods, as the name implies, there is no method name, only the method parameters and methods of the algorithm, can be really simple enough.
Also, we can use it directly Lamuda expression, directly constructs a method, as follows :
P1. Myadd = (int a, int b) = = {Console.WriteLine (a + b);};
The advent of anonymous methods and lambda expressions makes writing methods easier.
. NET basic literacy-small example string delegate, anonymous method, Lamuda expression