您的位置:首页 > 编程语言 > C#

C# Lambda表达式

2012-09-27 10:16 225 查看
一、概念

Lambda 表达式是一种匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。

二、格式

格式为:(参数列表)=>表达式或者语句块。

可以有多个参数,一个参数,或者无参数。参数类型可以隐式或者显式。例如:

(x, y) => x * y //多参数,隐式类型=> 表达式

x => x * 10 //单参数, 隐式类型=>表达式

x => { return x * 10; } //单参数,隐式类型=>语句块

(int x) => x * 10 // 单参数,显式类型=>表达式

(int x) => { return x * 10; } // 单参数,显式类型=>语句块

() => Console.WriteLine() //无参数

三、Lambda 表达式的简单应用

使用lambda表达式的时候,不得不提到泛型委托。在上面我们定义的表达式如:(x,y)=>x*y,返回的是一个委托;

1、如何调用定义的表达式:

可以定义自己的函数委托 (C# 1.0和2.0)

可以使用.NET类库中已经提供的泛型委托Func<T>(C#3.0)

2、实例:

View Code

class Program

{
static void Main(string[] args)

{

Expression<Func<int, bool>> filter = m=> (m * 4) < 2;

BinaryExpression lt = (BinaryExpression)filter.Body;

BinaryExpression mult = (BinaryExpression)lt.Left;

ParameterExpression en = (ParameterExpression)mult.Left;

ConstantExpression three = (ConstantExpression)mult.Right;

ConstantExpression five = (ConstantExpression)lt.Right;

var One = filter.Compile(); Console.WriteLine("Result: {0},{1}", One(5), One(1));

Console.WriteLine("({0} ({1} {2} {3}) {4})", lt.NodeType, mult.NodeType, en.Name, three.Value, five.Value);

Console.ReadLine();
}

}


效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: