C# 匿名函数
2019-03-23 本文已影响0人
CodeVin
匿名函数可在需要委托的任何地方使用。可以使用匿名函数来初始化委托实例。共有两种匿名函数:Lambda表达式 和 匿名方法。
下面的示例演示了从 C# 1.0 到 C# 3.0 委托创建过程的发展:
class Test
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
// Original delegate syntax required
TestDelegate testDelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
// C# 3.0. A delegate can be initialized with
TestDelegate testDelC = (x) => { Console.WriteLine(x); };
// Invoke the delegates.
testDelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Lambda表达式
Lambda表达式广泛应用于:
- 将要执行的代码传递给异步方法。如 Task.Run(Action)
- 编写LINQ查询表达式
- 创建表达式树
表达式lambda
表达式位于 => 运算符右侧的lambda表达式称为“表达式lambda”。表达式lambda会返回表达式的结果,并采用以下基本形式:
(input-parameters) => expression
括号内多个输入参数使用逗号加以分隔:
Func<int, int, bool> testForEquality = (x, y) => x == y;
语句lambda
语句lambda的语句在大括号中:
(input-parameters) => { statement; }
当只有一个输入参数时,小括号可以省略:
Action<string> greet = name =>
{
string greeting = $"Hello {name}!";
Console.WriteLine(greeting);
};
greet("World");
// Output:
// Hello World!
匿名方法
创建匿名方法实际上是一种将代码作为委托参数传递的方式,如下示例:
// Create a delegate.
delegate void Del(int x);
// Instantiate the delegate using an anonymous method.
Del d = delegate(int k) { /* ... */ };