Lambda表达式,是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。
Lambda表达式, 都是用"=>"运算符。 读作"goes to"。Lambda表达式运算符的左边是输入参数(如果有),右边包含表达式或语句块。使用格式如下:
(input parameters) => expression;
“Lambda表达式”是委托的实现方法,所以必须遵循以下规则:
-
1)“Lambda表达式”的参数数量必须和“委托”的参数数量相同;
-
2)如果“委托”的参数中包括有ref或out修饰符,则“Lambda表达式”的参数列中也必须包括有修饰符
大家都知道,一个类的私有成员只能在他的内部访问!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Lambda
{delegate bool D();delegate bool D2(int i);class Test{public D del;public D2 del2;public void TestMethod(int input){int j = 0;del = () => {j = 10;return j > input;};del2 = (x) =>{return x == j;};Console.WriteLine("j = {0}", j);bool boolResult = del();Console.WriteLine("j = {0}, b = {1}", j, boolResult); }}class Program{static void Main(string[] args){Test test = new Test();test.TestMethod(5); bool result = test.del2(10);Console.WriteLine(result);Console.ReadKey();}}
}私有成员,在类外面不能引用.
private int x;
Cla cla = new Cla()
cla.x 这样引用是错的
如果public int x;
Cla cla = new Cla()
cla.x 这样引用是对的
You can also create an anonymous method using an operator called lambda and represented by =>. From our example above, to use the lambda operator to create an anonymous method, omit the delegate keyword and follow the parentheses by the operator. Here is an example: