Lambda 表達式是一個匿名函數,是C# 3.0引入的新特性。Lambda 運算符=>,該運算符讀為“goes to”。C#為委托提供一種機制,可以為委托定義匿名方
法,匿名方法沒有名稱,編譯器會定指定一個名稱。匿名方法中不能使用跳轉語句跳轉到該匿名方法的外部,也不能跳轉到該方法的內部。也不能在匿名方法外部
使用的ref和out參數。
下面的代碼簡單的演示了Lambda表達式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions; //using
namespace Lambda
{
class Program
{
//委托方法
delegate string MyDelagate(string val);
static void Main(string[] args)
{
string str1 = "匿名方法外部\n";
//中括號部分定義了一個方法,沒有名稱,編譯器會自動指定一個名稱
MyDelagate my = (string param) =>
{
string str2 = "匿名方法內部\n";
return(param + str1 + str2);
};
//調用委托的匿名方法
Console.WriteLine(my("參數\n"));
//從結果可以看到,匿名方法同樣達到了為委托定義實現體方法的效果
Console.Read();
}
}
}
左邊是參數,使用括號表達 (string param),
右邊是實現代碼,使用花括號,如果代碼只有一行,則不使用花括號和return關鍵字也可以,編譯器會為我們添加。
這是λ表達式的簡單實現:
string str1 = " 匿名方法外部 ";
string str2 = " 匿名方法內部 ";
MyDelagate my = param => param + str1 + str2;
Console.WriteLine(my(" 參數 "));
private delegate int MyDelagate(int i);
MyDelagate test1 = x => x * x;
MyDelagate test2 = (x) => x * x;
MyDelagate test3 = (int x) => x * x;
MyDelagate test4 = (int x) => { return x * x; };
Console.WriteLine(test1(10));
Console.WriteLine(test2(10));
Console.WriteLine(test3(10));
Console.WriteLine(test4(10));private delegate int MyDelagate(int x, int y);
MyDelagate test1 = (x, y) => x * y;
MyDelagate test2 = (int x, int y) => x * y;
MyDelagate test3 = (int x, int y) => { return x * y; };
Console.WriteLine(test1(3,4));
Console.WriteLine(test2(3,4));
Console.WriteLine(test3(3,4)); private delegate void Void();
void test11 = () => { Console.WriteLine("Void Params"); };
test11();