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
效果:
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(); } }
效果:
相关文章推荐
- 为LINQ服务的C#新特性总结篇---扩展方法,匿名委托,lambda表达式,Action委托,Func委托,Linq中的order by,top和sum函数
- C# 3.0新特性体验之Lambda表达式
- C# => Lambda表达式理解
- C# 3.0新特性体验之Lambda表达式_C#教程
- C#中Lambda表达式
- C++ 和 C# 二者 Lambda 表达式之异同
- C#笔记(四):Lambda 表达式
- 将Lambda表达式作为参数传递并解析——在构造函数参数列表中使用Lambda表达式(C#)
- Lambda 表达式(C# 编程指南)
- Lambda 表达式(C# 编程指南)
- Lambda 表达式(C# 编程指南)
- 你知道C#中的Lambda表达式的演化过程吗?
- C# Lambda表达式
- C# Lambda 表达式
- Lambda 表达式(C# 编程指南)
- C#Lambda表达式的用法
- C#编程(四十三)----------Lambda表达式
- C# 委托-lambda表达式
- C#特性 学习笔记(Lambda表达式 迭代)
- C#学习笔记一:委托、匿名函数、Lambda 表达式