Learn to delegate as a beginner:
1. Define a delegate: a delegate is actually a class that knows the return type of the method and the parameter type of the method before the delegate is defined (the delegate can be understood to know only the return type of the method and the parameter type of the method, without knowing the method body)
Public delegate string Testdelegate (string test);
2. Example:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Namespace Demo
{
Public delegate string Testdelegate (string name);//define Delegate, delegate is actually a class
Create a new class to test the delegate invocation method
public class Test
{
public void Greetpeople (string name, Testdelegate delegate1)
{
if (delegate1! = null)//If there is a method to register a delegate variable
//{
Delegate1 (name);//Call method by delegate
//}
Delegate1?. Invoke (name);//(equivalent to the IF above)
}
}
Class Program
{
private static string TestMethod (string name)
{
Console.WriteLine ("Hello," + name);
return null;
}
static void Main (string[] args)
{
Test GM = new test ();
Invoking the TestMethod method with a delegate
gm. Greetpeople ("Panter", TestMethod);
Console.WriteLine ();
Invoking a lambda using a delegate
Console.Write ("Using lambda:");
gm. Greetpeople ("pant", Lambdatest =
{
Console.WriteLine ("Hello," +lambdatest);
return null;
});
Console.readkey ();
}
}
}
Results:
C # A preliminary understanding of delegates