Simple delegate instance delegate

Keywords: C# .NET

Delegate is a type of stored function reference, which is important in event and event processing

Generally speaking, a delegate is a type that can reference a method. When a delegate is created, a variable that references the method is created, and then the method can be called, that is, the delegate can call the method it refers to.

  1. Use delegation

The use of delegation requires the following steps:

Define delegate

delegate double ParocessDelegate(double param1,double param2);

The definition of a delegate is very similar to a function, but without the function body, and uses the delegate keyword. The delegate definition needs to specify the delegate name, a return type and a parameter list

Declare variables of delegate type

ProcessDelegate process;

After defining a delegate, you can declare a variable of the delegate type

Initializing delegate variables

process =new ProcessDelegate(Multiply);

When initializing a delegate variable, a function (here Multiply is the name of a function) reference should be assigned to the delegate variable. This function needs to have the same return type and parameter list as the delegate. c# using the above slightly odd syntax, use the new keyword to create a new delegate with the parameter
To reference the required function, this is a unique syntax for delegate assignment, and the function name is not bracketed

You can also use another slightly simpler syntax

process = Muiltiply;

With the delegate variable of the reference function, we can call the Muiltiply function with the delegate variable; You can also pass delegate variables to other functions

process (param1,param2);

Example:

namespace Delegate
{

        public delegate int Call(int num1, int num2);//Step 1: define the delegate type
        class SimpleMath
        {
            // Multiplication method
            public int Multiply(int num1, int num2)
            {
                return num1 * num2;
            }

            // Division method
            public int Divide(int num1, int num2)
            {
                return num1 / num2;
            }
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            Call objCall;//Step 2: declare delegate variables
            // Objects of the Math class
            SimpleMath objMath = new SimpleMath(); 
            // Step 3: initialize the delegate variable and associate the method with the delegate
            objCall = new Call(objMath.Multiply);

           
            objCall += objMath.Divide;//Add a method to the delegate
            //objCall -=  objMath.Divide;// Subtract a method from the delegate

            // Call the delegate instance, execute objMath.Multiply first, and then objMath.Divide
            int result = objCall(5, 3);
            System.Console.WriteLine("The result is {0}", result);
            Console.ReadKey();
        }
    }

matters needing attention:

  • Delegates can call multiple methods, that is, a delegate variable can reference multiple functions, which is called multicast
  • You can use the + = and - = operators to increase and decrease methods
  • A delegate with no return value will execute as many methods as it references. A delegate with a return value will also execute multiple referenced methods, but the return value is the return value of the last method

   2.   Other forms of entrustment

  • anonymous delegate

Anonymous delegates are simpler to use. They do not need to define a special delegate function to pass methods, and they can better understand delegates

//Define delegate
    delegate string lookMe(string s);

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        //anonymous delegate 
        lookMe lm = delegate(string name) { return "dear " + name + ",Please look into my eyes!"; };

        //Anonymous delegate call
        string name1 = "jarod";
        Label1.Text = lm(name1);
    }

  • generic delegate

Action < >, func < >, predict < > in fact, they are all short forms of principal-agent. Through them, the steps of defining delegation can be omitted

Example

public static void HellowChinese(string strChinese)  
{  
    Console.WriteLine("Good morning," + strChinese);  
    Console.ReadLine();  
}  
  
Action<string> action = HellowChinese;  
action("Spring.");  

Action is a generic delegate without return value, Func is a generic delegate with return value, and predicate < > is a delegate that returns bool type. They all have overloaded versions of multiple parameters

    three    Various expressions of entrustment

public delegate int DelegateProcess(int num1, int num2);

//The first way to write
DelegateProcess process= new DelegateProcess(Multiply);

//The second way to write
DelegateProcess process= Multiply;

//The third way is anonymous delegation
DelegateProcess process= delegate(int a,int b)
{
   return a*b;
}

//The fourth method is Lamdba expression
DelegateProcess process =((int a,int b)=>{return a*b;});

//The fifth way is action < T > and func < T >
Action<int,int> process= ((int a,int b)=>{Console.WriteLine(a * b);});
Func<int,int,int> process= ((int a,int b)=>{return a*b;});

Posted by richardk1 on Fri, 19 Nov 2021 09:56:06 -0800