[Reading Notes] C # Commission

Source: Internet
Author: User
Tags sharpdevelop

Conclusion: Use a delegate when you think you need to call a method.

. Net implements function pointers in the form of delegation, but delegation is also type-safe.

In C and C ++, only the function address can be extracted and transmitted as a parameter. C is non-secure. You can transmit any function to a method that requires a function pointer. This causes some problems, such as type security. During object-oriented programming, methods do not exist in isolation and need to be associated with instances before calling. To pass a method, you must encapsulate the details of the method in a new type object, which is the delegate.

Delegation is mainly used in the following three aspects:

    • Start thread
    • General Class Library
    • Event

Example 1:

/** Created by sharpdevelop. * User: Administrator * Date: 2010-3-15 * Time: 20:19 ** to change this template use tools | options | coding | edit standard headers. */using system; namespace delegate1 {class program {private delegate string getastring (); public static void main (string [] ARGs) {int x = 40; getastring firststringmethod = new getastring (X. tostring); console. writeline ("string is {0}" + firststringmethod (); // todo: implement functionality hereconsole. write ("press any key to continue... "); console. readkey (true );}}}
 
In C #, the delegate is always a constructor with a parameter in syntax. this parameter is the delegate reference method. You need to use the instance and method name to correctly initialize the delegate. X. tostring
 
The brackets provided to the delegate instance are identical to the invoke () method used to call the delegate.
 
Firststringmethod () ;=== firststringmethod. Invoke ();
 
 
 
A simple example of delegation:
/** Created by sharpdevelop. * User: Administrator * Date: 2010-3-15 * Time: 20:52 ** to change this template use tools | options | coding | edit standard headers. */using system; namespace delegate2 {class mathoperations {public static double multiplebytwo (double value) {return value * 2;} public static double square (double value) {return value * value ;}} class program {delegate double doubleop (Double X); public static void main (string [] ARGs) {doubleop [] operations = {mathoperations. multiplebytwo, mathoperations. square}; For (INT I = 0; I <operations. length; I ++) {console. writeline ("using operations [{0}]:", I); processanddisplaynumber (Operations [I], 2.0); processanddisplaynumber (Operations [I], 7.94 ); processanddisplaynumber (Operations [I], 1.414);} console. write ("press any key to continue... "); console. readkey (true);} static void processanddisplaynumber (doubleop action, double value) {double result = action (value); console. writeline ("value is {0}, result of operation is {1}", value, result );}}}

The running result is as follows:

 
 
 
 
 
Analysis of Typical commissioned practical cases:
 
Bubble Sorting:
 
The process of Bubble Sorting is very simple. The source code is as follows:
 
For (INT I = 0; I <sortarray. length; I ++) for (Int J = I + 1; j <sortarray. length; j ++) {If (sortarray [I] <sortarray [J]) {int temp = sortarray [I]; sortarray [I] = sortarray [J]; sortarray [J] = temp ;}}
 
This is the sorting of an int array. Now the goal is to expand the sorting process and sort all objects. In this case, there is a problem. sortarray [I] <sortarray [J] cannot simply compare any object. Assuming that employees of the Company are sorted by salary order, what can we do?
 
First, the Bubble Sorting class must call a method that compares two objects.
 
Delegate bool comparison (Object X, object y); static public void sort (object [] sortarray, comparison)
 
 
 however, sort cannot exist independently, so the following class exists. 
/** Created by sharpdevelop. * User: Administrator * Date: 2010-3-15 * Time: 21:27 ** to change this template use tools | options | coding | edit standard headers. */using system; namespace delegate3 {class employee {private string name; private decimal salary; public employee (string name, decimal salary) {This. name = Name; this. salary = salary;} public override string tostring () {return string. format ("{0}, {1: c}", name, salary);} public static bool comparesalary (Object X, object y) {employee e1 = (employee) X; employee e2 = (employee) y; Return (e1.salary <e2.salary) ;}} delegate bool comparison (Object X, object y ); class bubblesorter {static public void sort (object [] sortarray, comparison) {for (INT I = 0; I <sortarray. length; I ++) for (Int J = I + 1; j <sortarray. length; j ++) {If (comparison (sortarray [I], sortarray [J]) {object temp = sortarray [I]; sortarray [I] = sortarray [J]; sortarray [J] = temp ;}}} class program {public static void main (string [] ARGs) {employee [] employees = {New Employee ("Bugs Bunny", 2000), new employee ("Elmer Fudd", 10000), new employee ("Daffy Duck", 2500 ), new Employee ("Wiley coyte", (decimal) 10456.89), new employee ("fghon Leghorn", 23000),}; bubblesorter. sort (employees, employee. comparesalary); foreach (VAR employee in employees) {console. writeline (employee);} // todo: implement functionality hereconsole. write ("press any key to continue... "); console. readkey (true );}}}

 
 
 
In this example, improvements are needed.
 
Public static bool comparesalary (Object X, object y) {employee e1 = (employee) x; employee e2 = (employee) y; Return (e1.salary <e2.salary );}
The above sectionCodeIt appears in the employee class, and there is no need to use objects for parameters. You can consider writing the following statements, which is more concise.
Public static bool comparesalary (employee X, employee y) {return (X. Salary <Y. Salary );}
Sorry, it seems that you are smart. Delegate bool comparison (Object X, object y); declares whether to call the object class, delegate or type security. The above method cannot be changed!

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.