一句话说明白lamda表达式
lamda表达式
格式:( 形参列表 ) => { 函数体 }
作用:简化匿名方法的书写,可用在任何可使用匿名方法和强类型代理的地方;
例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lamda_expression
{
class Program
{
public delegate string mydelegate(string s);
static void Main(string[] args)
{
mydelegate d1;
d1 = delegate(string myarg) { Console.WriteLine("anonymous method output: {0}", myarg); return "anonymous method done"; };
d1 += ((string myarg) => { Console.WriteLine("lamda expression output: {0}", myarg); return "lamda ok"; });
Console.WriteLine("d1 output: {0}", d1("arg"));
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lamda_expression
{
class Program
{
public delegate string mydelegate(string s);
static void Main(string[] args)
{
mydelegate d1;
d1 = delegate(string myarg) { Console.WriteLine("anonymous method output: {0}", myarg); return "anonymous method done"; };
d1 += ((string myarg) => { Console.WriteLine("lamda expression output: {0}", myarg); return "lamda ok"; });
Console.WriteLine("d1 output: {0}", d1("arg"));
}
}
}
输出:
anonymous method output: arg
lamda expression output: arg
d1 output: lamda ok
lamda expression output: arg
d1 output: lamda ok
从上面的输出还可以看到,d1代理了多个方法,只有调用序列中最后一个方法的返回值作为d1的返回值。
非常详细的说明:http://www.cnblogs.com/smwikipedia/archive/2009/05/06/1450825.html
posted on 2009-09-28 19:24 smwikipedia 阅读(1750) 评论(1) 编辑 收藏 举报