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

三种方法实例化委托

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值