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);
}
}
C#中的Lambda表达式:表达式、语句与异步操作
本文介绍了C#中的Lambda表达式,包括表达式lambda、语句lambda和异步lambda。通过示例展示了如何使用它们来创建函数式和异步操作,如求平方、打印输出和立方计算。同时,展示了如何在事件处理中使用异步lambda,等待异步方法并更新UI。
1455

被折叠的 条评论
为什么被折叠?



