之前的.NET委托篇里提过lambda委托,这里对lambda进行浅析,进一步全面的来阐述下lambda的应用。
Lambda表达式常见的是用于创建匿名委托函数,LINQ查询表达式中等。通过使用Lambda,我们可以使本地的函数像参数一样被传递,被返回。
表达式lambda:
下面展现几种常见的lambda形式,表达式lambda会返回表达式的结果。
1:
(input-parameters)=>expression
当参数只有一个时,括号是可选的。当参数是多个时,括号时必须的。例如:
(x,y) => x == y
有时候编译器无法解释其类型,需要我们指明:
(string s,int i) => s.Length + i
可见lambda表达式还是比较简单易于识别的。
语句lambda:
(input-paramters)=>{statements;};
其实着时候就有点匿名函数的感觉了。例如:
class Test
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
// Original delegate syntax required
// initialization with a named method.
TestDelegate testDelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
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();
}
}
/* Output:
Hello. My name is M and I write lines.
That's nothing. I'm anonymous and
I'm a famous author.
Press any key to exit.
*/
其实Lambda常用的集中形式上面基本都展示了。