C# study notes Action and Func

Well defined in the system some common commission, which is System.Action, and System.Functhe former did not return function values, which is expressed the function return value. In order to adapt to the number of different parameters, the system defines a series of Actionand Func, as shown in the following figure:
Insert picture description here
Among them, the parameter type of each delegate can be customized when used, that is, a generic type is used, such as indicating two integers as parameters , Returns a doubletype, it can be expressed as:

	Func<int, int, double> f = (x, y) => x * 3.0 + y * 2.0;

Another example is voida function with only one string parameter and return type . This can be expressed as:

	Action<string> print = s => Console.WriteLine(s);

Or without parameters Action:

	Action showTime = () => Console.WriteLine(DateTime.Now);

Delegates and Lambda expressions are generally used as function parameters. For example, the system has a ForEachfunction that can Listprocess each element of a list ( ), and that this "processing" is a Actiondelegate type, you can use it A Lambda expression as a parameter. ForEachThe prototype of the function is:

	List<T>.ForEach(Action<T> a)

Example ListForEach.csshiyongLambdaexpressions ForEachare used as parameters to display and find the total number of letters in a word:

public class ListForEach
{
    
    
	static void Main(){
    
    
		List<string> words = new List<string>(){
    
    
			"Apple", "Banana", "Orange", "Mango"};
		words.ForEach(s => Console.WriteLine(s));

		int letters = 0;
		words.ForEach(s => letters += s.Length);
		Console.WriteLine(letters);
	}
}

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114050779