c# 匿名方法

来源:互联网 发布:太平洋网络股票 编辑:程序博客网 时间:2024/06/05 10:53

匿名方法是在初始化委托时内联声明的方法。

例如下面这两个例子:

不使用匿名方法的委托:

复制代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication7{    class Program    {        public static int add(int x)        {            return x + 20;        }        delegate int otherdel(int param);        public static void Main()        {            otherdel del = add;            Console.WriteLine("{0}", del(20));            Console.WriteLine("{0}", del(10));        }    } }
复制代码

 

使用匿名方法的委托:

复制代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication7{    class Program    {        delegate int otherdel(int param);        public static void Main()        {            otherdel del = delegate(int x)            {                return x + 20;            };            Console.WriteLine("{0}", del(20));            Console.WriteLine("{0}", del(10));        }    } }
复制代码

 

两种结果是一样的。

使用匿名方法

1)声明委托变量时候作为初始化表达式。

2)组合委托时在赋值语句的右边。

3)为委托增加事件时在赋值语句的右边。

匿名方法语法

delegate (parameters ){implementationcode};

关键字  参数        语句块

匿名方法不会声明返回值类型。但是匿名方法返回值类型必须和委托返回值一样。

 

参数:参数数量,类型和修饰符必须和委托一样。

但是我们可以使圆括号为空,或省略圆括号来简化匿名方法的参数列表。但是仅在下面两项都为真的情况下才可以这么做。

1,委托的参数列表不包含任何out参数的委托。

2,匿名方法不使用任何参数。

例如下面:

复制代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication7{    class Program    {        delegate int otherdel(int param);        public static void Main()        {            otherdel del = delegate            {                cleanup();                printMessage();            };                  }    } }
复制代码

 

 params参数:

如果委托参数包含params参数,那么params关键字就会被匿名方法的参数列表忽略。如下:

delegate int otherdel(int x,params int y);        otherdel del = delegate(int x,int y)        {            -------------        };
原创粉丝点击