Expression lambdas
=> 运算符右侧有表达式的 lambda 表达式称为表达式 lambda。
(input-parameters) => expression
Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
Action line = () => Console.WriteLine();
Func<double, double> cube = x => x * x * x;
Func<int, int, bool> testForEquality = (x, y) => x == y;
Func<int, string, bool> isTooLong = (int x, string s) => s.Length > x;
Statement lambdas
语句 lambda 类似于表达式 lambda,只是它的语句被括在大括号中:
(input-parameters) => { }
Action<string> greet = name =>
{
string greeting = $"Hello {name}!";
Console.WriteLine(greeting);
};
greet("World");
Async lambdas
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += async (sender, e) =>
{
await ExampleMethodAsync();
textBox1.Text += "\r\nControl returned to Click event handler.\n";
};
}
private async Task ExampleMethodAsync()
{
// The following line simulates a task-returning asynchronous process.
await Task.Delay(1000);
}
}