设为首页 加入收藏 网站搜索 繁體中文 中国建站网 — 站长资源分享平台

C# 3.0新特性体验之Lambda表达式

来源:网络收集 作者:佚名 时间:2007-04-26 00:48:23
  C#2.0介绍了一个新特性--匿名方法,允许开发者在线(inline)声明自己的函数代码而无须使用委托函数(delegate function)。C#3.0中提供了一个新特性--Lambda表达式,它提供了完成相同目标的更加简洁的格式。让我们在讨论Lambda表达式以前仔细研究一下匿名方法。

  匿名方法

  假设你需要创建一个按钮,当点击它的时候更新ListBox里的内容。在C#1.0和1.1里,你要这样做:

public MyForm()
{
 listBox = new ListBox(...);
 textBox = new TextBox(...);
 addButton = new Button(...);
 addButton.Click += new EventHandler(AddClick);
}

void AddClick(object sender, EventArgs e)
{
 listBox.Items.Add(textBox.Text);
}
  在C#2.0里,你需要这样做:

public MyForm()
{
 listBox = new ListBox(...);
 textBox = new TextBox(...);
 addButton = new Button(...);
 addButton.Click += delegate
 {
  listBox.Items.Add(textBox.Text);
};
  就像你看到的一样,你不必要特别的声明一个新方法来将它连接到一个事件上。你可以在C#2.0里使用匿名方法来完成同样的工作。C#3.0里介绍了一种更加简单的格式,Lambda表达式,你可以直接使用"=>"来书写你的表达式列表,后面跟上一个表达式或者语句块。

  Lambda表达式中的参数

  Lambda表达式中的参数可以是显式或者隐式类型的。在一个显式类型参数列表里,每个表达式的类型是显式指定的。在一个隐式类型参数列表里,类型是通过上下文推断出来的:

(int x) => x + 1 // 显式类型参数
(y,z) => return y * z; // 隐式类型参数
  Lambda演算实例

  下面的例子给出了两种不同的方法来打印出一个list中长度为偶数的字符串。第一种方法AnonMethod使用了匿名方法,第二种LambdaExample则是通过Lambda演算实现:

// Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;

namespace LambdaExample
{
 public delegate bool KeyValueFilter<K, V>(K key, V value);
 static class Program
 {

  static void Main(string[] args)
  {
   List<string> list = new List<string>();

   list.Add("AA");
   list.Add("ABC");
   list.Add("DEFG");
   list.Add("XYZ");
   Console.WriteLine("Through Anonymous method");
   AnonMethod(list);
   Console.WriteLine("Through Lambda expression");
   LambdaExample(list);

   Dictionary<string, int> varClothes= new Dictionary<string,int>();

   varClothes.Add("Jeans", 20);
   varClothes.Add("Shirts", 15);
   varClothes.Add("Pajamas", 9);
   varClothes.Add("Shoes", 9);
   var ClothesListShortage = varClothes.FilterBy((string name,
   int count) => name == "Shoes" && count < 10);
   // example of multiple parameters
   if(ClothesListShortage.Count > 0)
    Console.WriteLine("We are short of shoes");
   Console.ReadLine();
 }

 static void AnonMethod(List<string> list)
 {
  List<string> evenNumbers = list.FindAll(delegate(string i)
  { return (i.Length % 2) == 0; });
  foreach (string evenNumber in evenNumbers)
  {
   Console.WriteLine(evenNumber);
  }
 }

 static void LambdaExample(List<string> list)
 {
  var evenNumbers = list.FindAll(i =>(i.Length % 2) == 0); // example of single parameter
  foreach(string i in evenNumbers)
  {
   Console.WriteLine(i);
  }
 }
}

public static class Extensions
{
 public static Dictionary<K, V> FilterBy<K, V>
(this Dictionary<K, V> items, KeyValueFilter<K, V> filter)
 {
  var result = new Dictionary<K, V>();
  foreach(KeyValuePair<K, V> element in items)
  {
   if (filter(element.Key, element.Value))
    result.Add(element.Key, element.Value);
  }
  return result;
 }
 
}
}
  如果你安装了Visual Studio 2005 and LinQ Preview,你可以使用编辑器来编译程序。如果没有的话,可以使用命令行方式:

C:\Program Files\LINQ Preview\Bin\Csc.exe
/reference:"C:\Program Files\LINQ Preview\Bin\System.Data.DLinq.dll"
/reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll
/reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll
/reference:"C:\Program Files\LINQ Preview\Bin\System.Query.dll"
/reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll
/reference:"C:\Program Files\LINQ Preview\Bin\System.Xml.XLinq.dll"
/target:exe Program.cs
  中间语言结果显示

  打开ILDASM我们来查看一下程序,你将看到如图1所示的内容:


图1
  双击AnonMethod函数你将看到C#编译器产生的中间语言代码:

.method private hidebysig static void AnonMethod(class
[mscorlib]System.Collections.Generic.List`1<string> list)
cil managed
{
 // Code size 96 (0x60)
 .maxstack 4
 .locals init ([0] class [mscorlib]System.Collections.Generic.List
 `1<string> evenNumbers,

[1] [2]  下一页

Tags:

  • 好的评价 如果您觉得好,就请您
      0%(0)
  • 差的评价 如果您觉得差,就请您
      0%(0)
  • 相关文章
    广告赞助

    文章随便看看 设计素材 建站学院 网页模板 视频教程

    网友评论

    共有 0 位网友发表了评论,得分 0 分,平均 0 分    查看完整评论

    用户名: 查看更多评论

    分 值:100分 85分 70分 55分 40分 25分 10分 1分

    内 容:

             通知管理员 验证码: