c#进阶-5.匿名函数和lambad表达式、闭包

匿名函数

匿名函数就是没有名字的函数,基于委托和事件

语法:delegate(参数列表)
{
//逻辑
};

使用范围:
1.函数中传递委托参数时
2.委托或事件赋值时

具体代码:

class Program
    {
        static void Main(string[] args)
        {
            //无参无返回值
            Action action = delegate ()
              {
                  Console.WriteLine("匿名函数逻辑");
              };
            action += f;
            action();
            //有参无返回值
            Action<int,string> a2 = delegate (int a,string s)
              {
                  Console.WriteLine(a + " " + s);
              };
            a2(1, "abc");
            //有返回值
            Func<int, string> f3 = delegate (int a)
               {
                   return "zxc";
               };
            Console.WriteLine(f3(1));
            //匿名函数参数传递
            Test t = new Test();
            t.f1(100, delegate ()
             {
                 Console.WriteLine("匿名函数参数传递");
             });
            //匿名函数作为返回值
            Action ac2 = t.GetFunc();
            ac2();
            //一步到位
            t.GetFunc()();
            Console.ReadKey();
        }
        static void f()
        {
            Console.WriteLine("1");
        }
    }
    class Test
    {
        public Action action;
        //参数传递
        public void f1(int a,Action fun)
        {
            Console.WriteLine(a);
            fun();
        }
        //作为返回值
        public Action GetFunc()
        {
            return delegate ()
            {
                Console.WriteLine("匿名函数作为返回值");
            };
        }
    }

匿名函数的缺点:函数没有名字,就无法从委托容器中移除

lambad表达式

lambad表达式就是匿名函数的简写,就声明不一样,其他用法一致

语法:
(参数列表)=>
{
//逻辑
};

因为用法一致,只给出不一样的地方:

 //参数类型可以省略
            Action<int> a3 = (value) =>
              {
                  Console.WriteLine(value);
              };
            a3(50);

参数类型省略,偷懒罢了

闭包

闭包就是内层函数可以引用外层函数的变量,即使外出函数已经停止,也就是改变了变量的生命周期。

以下例子说明:

class Test
    {
        public event Action action;
        public Test()
        {
            int value = 10;
            action += () =>
            {
                Console.WriteLine("value:" + value);
            };
            
        }
        public void p()
        {
            action();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.p();
            Console.ReadKey();
        }
    }

只要action没有置空,value就一致存在

注意:该变量的值不是创建时的值,而是父类最终时的值

以下例子说明:

for(int i=0;i<10;i++)
            {
                action += () =>
                {
                    Console.WriteLine(i);
                };
            }

现象:
在这里插入图片描述
如果想要获取0-9,在for循环里创建临时变量存即可,这样每一层的临时变量就没有关系了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值