Description:
Encapsulate a method that has a parameter and returns the type value specified by the TResult parameter.
Syntax:
Public delegate TResult Func <T, TResult> (T arg );
Parameter type:
T: parameter type of the method encapsulated by this delegate.
TResult: return value type of the method encapsulated by this delegate.
Parameters:
Arg: Parameters of the delegate encapsulation method
Returned value: the return value of the method encapsulated by this delegate.
Note:
You can use this delegate to construct a method that can be passed in the form of parameters without explicitly declaring a custom delegate. This method must correspond to the delegate's method signature.
That is to say, the encapsulated method must have a parameter passed to it through a value and has a return value.
Note:
To reference a method with a parameter and return void, you need to use the generic Action <T> delegate.
The above only accepts a parameter with a returned value. In fact, the Func delegate has the following forms:
Public delegate TResult Func <TResult> (); public delegate TResult Func <T, TResult> (T arg); public delegate TResult Func <T1, T2, TResult> (T1 arg1, t2 arg2); public delegate TResult Func <T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3); public delegate TResult Func <T1, T2, T3, t4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4 );
That is, when we use one, two, three, and four parameters with a return value, we can use the defined delegate instead of defining the delegate.
Example:
Protected void Page_Load (object sender, EventArgs e) {List <int> list = new List <int> (); list. addRange (new int [] {7, 6, 10, 1, 2, 3, 4, 5, 8}); Func <int, bool> fi = new Func <int, bool> (MoreThan5); IEnumerator <int> ie = list. where <int> (fi ). getEnumerator (); // effect and list. where <int> (fi ). getEnumerator () consistent // IEnumerator <int> ie = list. where <int> (x => x> 5 ). getEnumerator (); // effect and list. where <int> (fi ). getEnumerator () consistent // IEnumerator <int> ie = list. where (delegate (int I) {return I> 5 ;}). getEnumerator (); while (ie. moveNext () {Response. write (ie. current. toString () + "<br/>") ;}} public static bool MoreThan5 (int I) {return I> 5 ;}
Page output:
7
6
10
8
Func <T, TResult> generic delegation