Usage and difference of c# action, delegate and func

Posted by Backara_Drift on Mon, 01 Nov 2021 11:15:09 +0100

In the past, I used to write delegates by defining a delegate, but recently I saw that some foreigners wrote the source code in the form of action and func. At that time, I felt very strange to this, so I felt strange to look at the origin code, so I spent time learning these two methods, and then found that the code was a lot simpler. We can also use these two methods slowly in the process of practice.

Let's talk about the entrustment first:

Simulate the scene: Xiao Ming's learning mood is high recently. The books he bought before can't satisfy his desire. He plans to buy one (a programmer's self-cultivation). However, in the past, he always went to the book factory to buy, nm which was too far to carry, so he went to the nearby bookstore to buy. Xiao Ming went to give money and got a book back. This process is entrustment. Start analysis

1: Xiao Ming wants to buy a book on self-cultivation of a programmer (xx book is not bought) mandatory requirements (this is to define the nature of entrustment)

code:

private delegate void BuyBook();

2: Nearby bookstore (entrusted method)

code:

public static void Book()
{
    Console.WriteLine("I provide books");
}

3: Xiaoming establishes a relationship with the bookstore (binding method to the delegate)

code:

 BuyBook buybook = new BuyBook(Book);

4: Xiao Ming gives money to get books (trigger)

buybook();

The above content is to understand the usage of delegation. Next, I will start to explain Action and Func

Usage of Action

1: Xiao Ming is very distressed. I just buy a book, which makes me define it every time. I'm so bored. Is there a way not to define the entrustment? Well, is there really, the Action we're talking about today

Action BookAction = new Action(Book);
BookAction();

Is it a lot easier

2: Xiao Ming is not satisfied now. I have finished reading a programmer's self-cultivation. Now I want to buy another book. What should I do? Should I redefine the entrustment. In fact, you don't need to. You just need to thread the parameters. Let's look at the usage of action < T >

 static void Main(string[] args)
        {
            Action<string> BookAction = new Action<string>(Book);
            BookAction("Hundred years of solitude");
        }
 
        public static void Book(string BookName)
        {
            Console.WriteLine("I buy books:{0}",BookName);
        }

3: Now Xiao Ming has changed his mind. I not only have to choose books by myself, but also buy them from a powerful book manufacturer. Is there such a way? Then I tell you, action < in T1, in T2 >

static void Main(string[] args)
        {
            Action<string,string> BookAction = new Action<string,string>(Book);
            BookAction("Hundred years of solitude","Beijing big bookstore");
        }
 
        public static void Book(string BookName,string ChangJia)
        {
            Console.WriteLine("I buy books:{0}come from{1}",BookName,ChangJia);
        }

Func usage

Xiao Ming has another question. Every time I go to the bookstore to get the books, is there a way to send them directly to my home? Func specifically provides such a service

Func interprets and encapsulates a method that does not necessarily have parameters (perhaps none) but returns the type value specified by the TResult parameter.

1: Let's first look at a method with no parameters and only return values

 static void Main(string[] args)
        {
            Func<string> RetBook = new Func<string>(FuncBook);
            Console.WriteLine(RetBook);
        }
 
        public static string FuncBook()
        {
            return "Here comes the book";
        }

2: Methods with parameters and return values

static void Main(string[] args)
{
    Func<string,string> RetBook = new Func<string,string>(FuncBook);
    Console.WriteLine(RetBook("aaa"));
}
 
public static string FuncBook(string BookName)
{
    return BookName;
}

3: A very important use of Func is to pass values. Let me give a simple code to illustrate

 Func<string> funcValue = delegate
            {
                return "I am the value 3 to be passed";
            };
 
            DisPlayValue(funcValue);

Note 1: displayvue refers to the processing of the transmitted value, which refers to the processing of cache, or the unified addition of database, etc

 private static void DisPlayValue(Func<string> func)
{
            string RetFunc = func();
            Console.WriteLine("I'm testing the value passed:{0}",RetFunc);
        }

summary

1: Action is used for methods with no return value (parameters can be passed according to their own situation)

2: Func is just the opposite. It is used for methods with return values (the same parameters depend on your own situation)

3: Remember to use action if there is no return and Func if there is a return