C#中的匿名函数

发布时间:2026/7/29 2:21:36
C#中的匿名函数 C#中的匿名函数顾名思义即为没有名字的函数采用delegate关键字来声明必须搭配委托和事件来使用常常作为在函数中进行传递的参数或是返回值以及对委托和事件的赋值中匿名函数必然要有一个委托或是事件来装载其缺点在于对于多播委托或事件容器无法指定性移除其中的某个函数。using System; using System.Collections.Generic; namespace lesson13 { class Test { public Action action; public void DoSomething(int a, Action action) { Console.WriteLine(a); action(); } //匿名函数作为函数的返回值 public Action GetFun() { return delegate () { Console.WriteLine(函数内部返回的逻辑); }; } } class Program { static void Main(string[] args) { //无参无返回值的匿名函数的声明(必须要用委托来存储) Action a delegate () { Console.WriteLine(aaa); }; a(); //有参数的匿名函数的声明 Actionint,string b delegate (int value, string b) { Console.WriteLine(a); Console.WriteLine(b); }; b(3, abc); //有返回值的匿名函数的声明 Funcstring c delegate () { return 123123; }; Console.WriteLine(c()); Test t new Test(); //匿名函数作为参数传入使用 t.DoSomething(100, delegate () { Console.WriteLine(随参数传入的匿名函数逻辑); }); Action ac t.GetFun(); ac(); t.GetFun()();//一步到位的写法 } } }