Well defined in the system some common commission, which is System.Action
, and System.Func
the 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 Action
and Func
, as shown in the following figure:
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 double
type, it can be expressed as:
Func<int, int, double> f = (x, y) => x * 3.0 + y * 2.0;
Another example is void
a 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 ForEach
function that can List
process each element of a list ( ), and that this "processing" is a Action
delegate type, you can use it A Lambda expression as a parameter. ForEach
The prototype of the function is:
List<T>.ForEach(Action<T> a)
Example ListForEach.csshiyongLambda
expressions ForEach
are 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);
}
}