什么是匿名函数
顾名思义,就是没有名字的函数
匿名函数的使用主要是配合委托和事件进行使用
脱离委托和事件 是不会使用匿名函数的
基本语法
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全清 )