Lambda 表達式是一種可用於創建委托或表達式目錄樹類型的匿名函數。
通過使用 lambda 表達式,可以寫入可作為參數傳遞或作為函數調用值返回的本地函數。
Lambda 表達式對於編寫 LINQ 查詢表達式特別有用。
若要創建 Lambda 表達式,需要在 Lambda 運算符 => 左側指定輸入參數(如果有),然後在另一側輸入表達式或語句塊。
例如,lambda 表達式 x => x * x 指定名為 x 的參數並返回 x 的平方值
using System;
namespace NewAttr
{
/// <summary>
/// Lambda 表達式是一種可用於創建委托或表達式目錄樹類型的匿名函數。
/// Lambda 表達式對於編寫 LINQ 查詢表達式特別有用。
/// </summary>
public class LambdaDemo
{
public LambdaDemo() { }
/// 委托不能重載,即委托名稱相同,參數類型,個數不同。
/// 構造委托的時候,根本不管參數,當然也就不知道你要構造的是哪個委托。
private delegate int del(int x);
private delegate int del2(int x, int s);
private delegate void del3();
public static void Test()
{
del myDel1 = x => x * x;
del myDel2 = (x) => x * x;
del myDel3 = (x) => x * x;
del myDel4 = (int x) => x * x;
del myDel5 = (int x) => { return x * x; };
Console.WriteLine("del myDel1 = x => x * x :{0}", myDel1(2));
Console.WriteLine("del myDel2 = (x) => x * x :{0}", myDel2(2));
Console.WriteLine("del myDel3 = (x) => x * x :{0}", myDel3(2));
Console.WriteLine("del myDel4 = (int x) => x * x :{0}", myDel4(2));
Console.WriteLine("del muDel5 = (int x) =>{1}:{0}", myDel5(2), " { return x * x; } ");
del3 myDel6 = () => Test2();
Console.WriteLine("--------------------------------");
myDel6();
}
public static void Test2()
{
del2 myDel2 = (x, y) => x * y;
del2 myDel3 = (int x, int y) => x * y;
del2 myDel4 = (int x, int y) => { return x * y; };
Console.WriteLine("del2 myDel2 = (x, y) => x * y :{0}", myDel2(2, 2));
Console.WriteLine("del2 myDel3 = (int x, int y) => x * y :{0}", myDel3(2, 2));
Console.WriteLine("del2 myDel4 = (int x, int y) => {1} :{0}", myDel4(2, 2), "{ return x * y; }");
Console.WriteLine("--------------------------------");
FunTest();
}
public static void FunTest()
{
///其中 Func 是最多具有十六個輸入參數的任何一個 Func 委托
///之後一個為返回值。
///Func<TResult>,Func<T,TResult>,Func<T,.....T,TResult>
Func<int> myFunc = () => 1;
Console.WriteLine("Func<int> myFunc = () => 1 :{0}", myFunc());
Func<int, string, int> myFunc2 = (x, y) => x + y.Length;
Console.WriteLine("Func<int, string, int> myFunc = (x, y) => x + y.Length :{0}", myFunc2(1, "jasonhua"));
///其中 Action 是最多具有十六個輸入參數的任何一個 Action 委托
Action myAction = () => { Console.WriteLine("Action myAction :1 * 1"); };
myAction();
Action<int, int> myAction2 = (x, y) => { Console.WriteLine("Action<int, int> myAction2 = (x, y) :{0}", x * y); };
myAction2(1,1);
}
}
}