lambda lambda树 泛型委托 委托
官方:lambda 表达式是一个可用于创建委托或表达式树类型的匿名函数。 通过使用 lambda 表达式,可以可作为参数或返回编写本地函数,该函数调用的值。 Lambda 表达式用于编写 LINQ 查询表达式特别有用。
泛型委托:
Func<> 有返回值,返回类型TResult :
public delegate TResult Func<out TResult>(); public delegate TResult Func<in T, out TResult>(T arg); public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2); ... public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
共17个定义
Action<> 无返回值:
public delegate void Action<in T>(T obj); public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2); ... public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
共16个定义
对于无参数,无返回值的委托,可以用非泛型委托:
public delegate void Action();
一般在程序中这34个委托类型足够使用了。
16个参数以内(包括16个)的任何lambda表达式都一定可以赋值给这34种委托类型中合适的那一种的委托变量。
如:
Action lambda1 = () => { }; Action<int> lambda2 = n => { }; Func<bool> lambda3 = () => true; Func<int, bool> lambda4 = n => n > 0;
等。
如果超过16个参数,需要用delegate了:
delegate bool myTest(int p1,int p2,int p3,int p4,int p5,int p6,int p7,int p8,int p9,int p10,int p11,int p12,int p13,int p14,int p15,int p16,int p17); myTest lambda5 = (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17) => true;