INTERNET APPLICATION DEVELOPMENT
MID MARKET ERP DEVELOPMENT
by Jacky Xu
When coding in C# Actions belong to the delegate family. Delegates give us a lot of power to hold references to methods to execute, but it needs some additional codes to define a new delegate for every situation in which you need one. Action<T> started in .NET 2.0, and then expanded through each version to eventually support Actions that take anywhere from 0 to 16 arguments in .NET 4.0 and that return no result. These are very handy because they quickly allow you to be able to specify that a method or class you design will perform an action as long as the method you specify meets the signature.
· Action – matches a method that takes no arguments and returns no value.
· Action<T> – matches a method that takes an argument of type T and returns no value.
· Action<T1, T2> – matches a method that takes an argument of type T1, a second argument of type T2, and returns no value.
· Action<T1, T2, …> – and so on up to 16 arguments and returns no value.
Below are some samples for delegate and Action:
In the previous code, instead of creating a new delegate type for Log, we can just use an Action<string>:
This makes it easy to store delegates of nearly any method signature as long as it returns void, and you don’t have to define a new delegate type every time you need one for a class or method.
And you also can name the variable in such a way to use it:
When the program calls the method “Process<T>” and without any exception, it will call the successCallback action you specified. You also can define an exception call back action in the same way to handle the error.