最近碰到了很多关于Action的一些代码,稍微看了下用法
Action的作用是封装一个函数,且该方法没有返回值(有返回值的函数无法被Action封装)。同时Action还支持不同参数数量的函数,通过泛型来实现。Action<T>代表Action所封装的函数是有一个参数,参数类型为T。同理,Action最多支持16个参数的函数委托,不过每个参数的数据类型都要写到泛型里。
不同参数类型的Action声明:
Action
Action<T>
Action<T,T>
Action<T,T,T> ......
Action其实是一个委托delegate,如果我们使用delegate去封装一个函数的话,首先是需要进行委托声明的,如下面的代码
1 namespace Delegate_Action 2 { 3 //自定义委托声明 4 public delegate void delegateFuntion(); 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Test t = new Test(); 10 delegateFuntion myFunction = t.Function; //函数封装 11 myFunction(); 12 13 return; 14 } 15 } 16 17 class Test 18 { 19 public void Function() 20 { 21 Console.WriteLine("Test Function!"); 22 } 23 } 24 }
可以看到第4行进行了委托声明的动作,而为了操作简便,Action委托就可以免去这一步骤
如果用Action进行封装的话,代码如下
1 namespace Delegate_Action 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Test t = new Test(); 8 Action myAction = t.Function; //直接到位 9 myAction(); 10 11 return; 12 } 13 } 14 15 class Test 16 { 17 public void Function() 18 { 19 Console.WriteLine("Test Function!"); 20 } 21 } 22 }
同时Action支持委托和匿名函数
1 namespace Delegate_Action 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Test t = new Test(); 8 Action myAction = delegate() { Console.WriteLine("Delegate Function!"); }; //直接到位 9 myAction(); 10 11 return; 12 } 13 }
最后就是Action可以通过参数的形式传递函数,这样就可以将Action用作回调函数(个人感觉用处最多的地方),代码如下
1 namespace Delegate_Action 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Test t = new Test(CallBackFuntion); 8 t.Function(); 9 10 return; 11 } 12 13 static void CallBackFuntion() 14 { 15 Console.WriteLine("Program Call Back Function!"); 16 } 17 } 18 19 class Test 20 { 21 Action callBack; 22 23 public Test(Action cb) 24 { 25 callBack = cb; 26 } 27 28 public void Function() 29 { 30 Console.WriteLine("Test Function!"); 31 callBack(); 32 } 33 } 34 35 //结果: 36 // Test Function! 37 // Program Call Back Function! 38 }