C # system delegate Action And Func,

Source: Internet
Author: User

C # system delegate Action And Func,

 

Action: encapsulate a method that does not have parameters and does not return values.

public delegate void Action()

Action <T>: the generic type of Action defines 1 to 16 input parameters, but there is still no return value. It is concluded that Action does not support return values, if you want to return a value, use another system to delegate Func

public delegate void Action<in T>(T obj)...public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>(T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14,T15 arg15,T16 arg16)

It can be seen that the definition of Action is very simple, but such a delegate is too often used. If you can define one at a time, you will feel too much repetitive work:

Custom delegate in the past:

Using System; using System. windows. forms; public delegate void ShowValue (); public class Name {private string instanceName; public Name (string name) {this. instanceName = name;} public void DisplayToConsole () {Console. writeLine (this. instanceName);} public void DisplayToWindow () {MessageBox. show (this. instanceName) ;}} public class testTestDelegate {public static void Main () {Name testName = new Name ("Koani"); ShowValue showMethod = testName. displayToWindow; showMethod ();}}View Code

Use Action directly:

Using System; using System. windows. forms; public class Name {private string instanceName; public Name (string name) {this. instanceName = name;} public void DisplayToConsole () {Console. writeLine (this. instanceName);} public void DisplayToWindow () {MessageBox. show (this. instanceName) ;}} public class testTestDelegate {public static void Main () {Name testName = new Name ("Koani"); Action showMethod = testName. displayToWindow; // delegate an Action with an anonymous method // Action showMethod = delegate () {testName. displayToWindow () ;}; // assign the lambda expression to the Action delegate instance // Action showMethod = () => testName. displayToWindow (); showMethod ();}}View Code

The use of Action <T> is similar, but the definition of Action <T> is special. It has a keyword In, what is In, according to the MSDN explanation:

 

I recommend that you have a deeper understanding of C # convolutional variables and inverters.

Func: encapsulate a method that does not have a parameter but returns the type value specified by the TResult Parameter

public delegate TResult Func<out TResult>()

Func <T>: The generics of Func also implement 1 to 16 input parameters and support return values.

public delegate TResult Func<in T, out TResult>(    T arg)...public delegate void Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(    T1 arg1,    T2 arg2,    T3 arg3,    T4 arg4,    T5 arg5,    T6 arg6,    T7 arg7,    T8 arg8,    T9 arg9,    T10 arg10,    T11 arg11,    T12 arg12,    T13 arg13,    T14 arg14,    T15 arg15,    T16 arg16)

 

The definition of Func is also simple and clear, just like Action, to simplify the code for "customer:

Custom delegate in the past:

Using System; using System. IO; delegate bool WriteMethod (); public class TestDelegate {public static void Main () {OutputTarget output = new OutputTarget (); WriteMethod methodCall = output. sendToFile; if (methodCall () Console. writeLine ("Success! "); Else Console. writeLine ("File write operation failed. ") ;}} public class OutputTarget {public bool SendToFile () {try {string fn = Path. getTempFileName (); StreamWriter sw = new StreamWriter (fn); sw. writeLine ("Hello, World! "); Sw. Close (); return true;} catch {return false ;}}}View Code

 

Now you can directly use Func:

Using System; using System. IO; public class TestDelegate {public static void Main () {OutputTarget output = new OutputTarget (); Func <bool> methodCall = output. sendToFile; // Func <bool> methodCall = delegate () {return output. sendToFile () ;}; use Func <TResult> with anonymous methods // Func <bool> methodCall = () => output. sendToFile (); assign the lambda expression to Func <T, TResult> delegate if (methodCall () Console. writeLine ("Success! "); Else Console. writeLine ("File write operation failed. ") ;}} public class OutputTarget {public bool SendToFile () {try {string fn = Path. getTempFileName (); StreamWriter sw = new StreamWriter (fn); sw. writeLine ("Hello, World! "); Sw. Close (); return true;} catch {return false ;}}}View Code

 

 

Through the definition, we can see that the definition of Func not only shows the keyword In, but also an Out keyword. The MSDN explanation is as follows (Out is often used as the output parameter of the method ):

 

I still recommend that you have a deeper understanding of C # covariant and inverter concepts related to a higher degree of Derivation or higher type.

 


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.