委托(3.匿名方法、lambda、闭包、foreach)

来源:互联网 发布:unity3d 画虚线 编辑:程序博客网 时间:2024/06/08 17:24

三种方法实例化委托

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication30{    class Program    {        static void Main(string[] args)        {            Action<string, string> action1 = test;            action1("静态方法实例委托", "HelloWorld");            Action<string, string> action2 = delegate(string str1,string str2)            {                Console.WriteLine(string.Format("{0}:{1}",str1,str2));            };            action2("匿名方法实例委托", "HelloWorld");            Action<string, string> action3 = (str1,str2)=>            {                Console.WriteLine(string.Format("{0}:{1}", str1, str2));            };            action2("lambda实例委托", "HelloWorld");        }        static void test(string str1, string str2)        {            Console.WriteLine(string.Format("{0}:{1}", str1, str2));        }    }}

可以看出来,最麻烦的是使用静态方法实例化委托。

匿名方法和lambda表达式,其实CIL中会创建是个随机名称的静态方法来实例化,效率上来说三种方式都一样,只是从语法简洁度来看,lambda是最好的

闭包

什么是闭包?

闭包其实就是说在lambda表达式内部访问表达式以外的成员。如下代码就是闭包

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication30{    class Program    {        static void Main(string[] args)        {            int val = 5;            Func<int> func = () => val;            val = 10;            Console.WriteLine(func());//10        }    }}

foreach

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            var values = new List<int>() { 10, 20, 30 };            var funcs = new List<Func<int>>();            foreach (var value in values)            {                funcs.Add(() => value);            }            foreach (var func in funcs)            {                Console.WriteLine(func());            }        }    }}

这段代码在4.0版本输出是 30 30 30,在4.0之上的版本输出是10 20 30,因为foreach其实是一个枚举器,foreach中的value是定义在枚举器外面的,所以是闭包。

0 0