欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > C# 匿名函数 delegate(参数...){ }

C# 匿名函数 delegate(参数...){ }

2024/10/24 14:25:20 来源:https://blog.csdn.net/m0_53393728/article/details/141535597  浏览:    关键词:C# 匿名函数 delegate(参数...){ }

什么是匿名函数


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

基本语法
            delegate (参数列表)
            {
               函数逻辑
            };


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

使用

 static void Main(string[] args){//1.无参无返回//这样申明匿名函数 只是在申明函数而已 还没有调用//真正调用它的时候 是这个委托容器啥时候调用 就什么时候调用这个匿名函数Action a = delegate (){Console.WriteLine("匿名函数逻辑");};a();//2.有参Action<int, string> b = delegate (int a, string b){Console.WriteLine(a);Console.WriteLine(b);};b(100, "123");//3.有返回值Func<string> c = delegate (){return "123123";};Console.WriteLine(c());//4.一般情况会作为函数参数传递 或者 作为函数返回值Test t = new Test();Action ac = delegate (){Console.WriteLine("随参数传入的匿名函数逻辑");};t.Dosomthing(50, ac);//  参数传递t.Dosomthing(100, delegate (){Console.WriteLine("随参数传入的匿名函数逻辑");});//  返回值Action ac2 = t.GetFun();ac2();//一步到位 直接调用返回的 委托函数t.GetFun()();
}class Test{public Action action;//作为参数传递时public void Dosomthing(int a, Action fun){Console.WriteLine(a);fun();}//作为返回值public Action GetFun(){return delegate() {Console.WriteLine("函数内部返回的一个匿名函数逻辑");};}
}

匿名函数缺点

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

            Action ac3 = delegate ()
            {
                Console.WriteLine("匿名函数一");
            };

            ac3 += delegate ()
            {
                Console.WriteLine("匿名函数二");
            };

            ac3();
         // 因为匿名函数没有名字 所以没有办法指定移除某一个匿名函数
       //   此匿名函数 非彼匿名函数 不能通过看逻辑是否一样 就证明是一个 
            //ac3 -= delegate ()
            //{
            //    Console.WriteLine("匿名函数一");
            //};
            ac3 = null;
            //ac3();

练习

写一个函数传入一个整数,返回一个函数

之后执行这个匿名函数时传入一个整数和之前那个函数传入的数相乘

返回结果

 class Program{public static void Main(){Console .WriteLine (  First(5)(3));}public static  Func<int,int> First(int a){return delegate (int b){return b * a;};}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com