Reference example: Learn Func <T, TResult> delegate, functresult
These days, ASP. net mvc was developed, during which information was searched and a brand new Func <T, TResult> delegate was found. This allows us to save and simplify a lot during development.
During the development process, We Need To concatenate a generic List <int> and concatenate All Integer int types into a string.
In this case, we will write a method:
Source code:
Public string ConnectToString (List <int> listInt) {StringBuilder _ sb = new StringBuilder (); listInt. forEach (delegate (int I) {_ sb. append (I. toString () ;}); return _ sb. toString ();}View Code
In the view, we can apply this method:
This is the most common method.
What if I use delegation? How to write? Then we can use the delegate keyword delegate to declare a method. The method parameter is List <int>:
public delegate string DelegateConnectToString(List<int> listInt);
In the view, we use this delegate:
In the above method, we use a new delegate in the conventional way. Below, we do not need to use a new delegate and directly use an anonymous method to replace it:
Source code:
Public DelegateConnectToString ConnectToString1 = delegate (List <int> listInt) {StringBuilder _ sb = new StringBuilder (); listInt. forEach (delegate (int I) {_ sb. append (I. toString () ;}); return _ sb. toString ();};View Code
In the view, we can use the following method:
In a later version. NET Framework, there is already a Func <T, TResult> delegate, you do not have to declare a custom delegate to use it, such as DelegateConnectToString (List <int> listInt ).
Therefore, you can write the code as follows:
Source code:
Public Func <List <int>, string> ConnectToString2 = delegate (List <int> listInt) {StringBuilder _ sb = new StringBuilder (); listInt. forEach (delegate (int I) {_ sb. append (I. toString () ;}); return _ sb. toString ();};View Code
Apply this method to the View: