C# 笔记8 匿名函数

什么是匿名函数

顾名思义,就是没有名字的函数
匿名函数的使用主要是配合委托和事件进行使用
脱离委托和事件 是不会使用匿名函数的

基本语法

delegate (参数列表)

{

    函数逻辑

};


何时使用?
1.函数中传递委托参数时
2.委托或事件赋值时 

使用

1. 无参无返回

//这样申明匿名函数 只是在申明函数而已 还没有调用
//真正调用它的时候 是这个委托容器啥时候调用 就什么时候调用这个匿名函数
Action action = delegate ()
{
   Console.WriteLine("匿名函数逻辑");
};

2.有参

Action<int, string> b= delegate (int a, string b)
{
    Console.WriteLine(a);
    Console.WriteLine(b);
};

3.有返回值

Func<string> c = delegate ()
{
    return "123123";
};

4.一般情况会作为函数参数传递 或者 作为函数返回值

 class Test
 {
     public Action action;
     //作为参数传递时
     public void Dosomthing(int a, Action fun)
     {
         Console.WriteLine(a);
         fun();
     }
     //作为返回值
     public Action GetFun()
     {
         //以前的写法
         //return Test1;
         //现在可以直接写
         return delegate () {
         Console.WriteLine("111");
         };
     }
     public void Test1()
     {

     }

 }


mian中:
internal class Program
{
    static void Fun()
    {
        Console.WriteLine("1323");
    }
    static void Main(string[] args)
    {

        Test test = new Test();
        //参数传递
        //以前的写法
        test.Dosomthing(100, Fun);
        //现在可以直接写
        test.Dosomthing(100, delegate ()
        {
          Console.WriteLine("1323");
        });
        //返回值
        //以前的写法
        Action a=test.GetFun();
        a();
        //一步到位 直接调用返回的 委托函数
        test.GetFun()();
    }
}
匿名函数的缺点

添加到委托或事件容器中后 不记录 无法单独移除 

因为匿名函数没有名字 所以没有办法指定移除某一个匿名函数

(不能通过 -= 移除,只能=null全清 )

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值