Common methods of C# Action and Func callback

catalogue

1, Introduction

2, Action

Example 1

Example 2

3, Func

Example 1

Example 2

end

1, Introduction

Action and Func generic delegates are actually one NET Framework predefined delegates, features introduced in 3.5. It basically covers all commonly used delegates, so it generally does not need to be re declared by the user. Action series generic delegates are delegates that do not return parameters. They can have up to 16 parameters or no parameters.

Func series delegates are those with return values, and can have up to 16 parameters; Tuple is a new feature introduced in C# 4.0, which needs to be based on NET Framework 4.0 or later. Tuples use generics to simplify the definition of a class Provides static methods for creating tuple objects. You can create up to 8 tuples, that is, octets.

2, Action

In fact, delegation is to call a method as a parameter. Action is one of them. Action as a parameter cannot have a return value. Parameters can be of any type or do not pass parameters.

Example 1

Call Action in a class

using System;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            test1.myAction();

            Console.ReadKey();
        }
    }

    public class Test1
    {
        public Action myAction = null;

        private void sayHi()
        {
            Console.WriteLine("fuck you!");
        }

        public Test1()
        {
            myAction = sayHi;
        }
    }
}

function:

This method is rarely used. The commonly used method of Action is usually used as and callback

Example 2

It is also recommended to execute callback after a series of operations.

using System;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            test1.Calculation(1, 2, ReceiveResult);

            Console.ReadKey();
        }

        private static void ReceiveResult(int res)
        {
            Console.WriteLine("The result of settlement is:" + res);
        }
    }

    public class Test1
    {
        public void Calculation(int x, int y, Action<int> call)
        {
            if (call != null)
            {
                call(x + y);
            }
        }
    }
}

function:

Replace the method with a Lambda expression. The effect is the same. For the usage of Lambda, please refer to: Click jump

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            test1.Calculation(1, 2, (int res) =>
            {
                Console.WriteLine("The result of settlement is:" + res);
            });

            Console.ReadKey();
        }
    }

    public class Test1
    {
        public void Calculation(int x, int y, Action<int> call)
        {
            if (call != null)
            {
                call(x + y);
            }
        }
    }
}

3, Func

In the above case of using Action, there is no return value after the callback is executed. This is because Action cannot receive the return value. What if you want to execute the callback and have a return value? Func is used to solve this problem.

Func must have a return value, otherwise an error will be reported, as shown in the following figure:

The return value is usually the last parameter. Refer to example 1. Func < int, float, string > myfunc = null. In this delegate, string is the return value. When passing parameters, only two parameters can be passed. If you write another parameter, an error will be reported, as shown in the following figure:

Example 1

Basic usage: func assigns values, executes delegates, and receives return values

using System;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            string userName = test1.MyFunc(15, 180.2f);
            Console.WriteLine(userName);

            Console.ReadKey();
        }
    }

    public class Test1
    {
        public Func<int, float, string> MyFunc = null;

        private string GetUserName(int age, float height)
        {
            if (age == 15 && height == 180.2f)
            {
                return "Zhang San";
            }
            return null;
        }

        public Test1()
        {
            MyFunc = GetUserName;
        }
    }
}

function:

Example 2

Pass func as a parameter of the method and execute the callback

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            Func<string> func = () => 
            {
                string name = "Zhang San";
                string feel = "Very energetic";
                string msg = name + feel;
                return msg;
            };
            test1.Calculation(10, 12, func);
            Console.ReadKey();
        }
    }

    public class Test1
    {
        public void Calculation(int x,int y, Func<string> sayFunc)
        {
            if(sayFunc != null)
            {
                int age = x + y;
                string msg = string.Format("Age:{0}ļ¼ŒFeelings about age:{1}", age, sayFunc());
                Console.WriteLine(msg);
            }
        }
    }
}

function:

The above code is only used as a reference. Readers can make an improvement according to their own needs.

end

If this post is useful to you, welcome to follow + like + leave a message, thank you

end

Keywords: C#

Added by baitubai on Mon, 21 Feb 2022 06:18:14 +0200