C # delegation details (3): Delegation implementation methods (continued)

Source: Internet
Author: User

4. In addition to defining a new delegate type for each parameter and return type, you can also use the <T> and Func <T> delegate. the generic delegate actions <T> and Func <T> provided by the. NET Framework provide overloading from no parameter to a maximum of 16 parameters, if the method needs to obtain more than 16 parameters, it must define its own delegate type, but this situation should be rare. The Action <T> class can call methods without return values, and Func <T> can call methods with return types. Therefore, for the delegate in the previous code example, you can use Func <double T, out Tresult> to implement: Func <double, double> operations = MathOperations. multiplyByTwo; equivalent to: delegate double Operations (double x); Operations operations = MathOperations. multiplyByTwo; that is, the definition of the delegate class is omitted. In the following example, a general Bubble Sorting Algorithm is implemented using a generic delegate to see what is different from a general Bubble Sorting Algorithm: copy the code class BubbleSorter {static public void Sort <T> (IList <T> sortArray, Func <T, T, bool> comparison) {bool swapped = true; while (swapped) {swapped = false; for (int I = 0; I <sortArray. count-1; I ++) {if (comparison (sortArray [I + 1], sortArray [I]) {T temp = sortArray [I]; sortArray [I] = sortArray [I + 1]; sortArray [I + 1] = temp; swapped = true ;} You can see that the code implementation is no different. The difference is the method signature. The first parameter type is IList <T>, which supports inputting various set data, the second input parameter is a delegate object, representing a method of object T to be sorted. This method compares the size of two objects T and returns a boolean value, for more information, see the following code. Copy the code class Student // object type to be sorted {public Student (string name, int salary) {this. name = name; this. age = salary;} public string Name {get; private set;} public int Age {get; private set;} public override string ToString () {return string. format ("{0}, {1: C}", Name, Age);} public static bool CompareAge (Student e1, Student e2) {return e1.Age <e2.Age ;}} class Program {static void Main () {St Udent [] students = {new Student ("zhangsan", 20), new Student ("lisi", 12), new Student ("wangwu", 25 ), new Student ("zhaoliu", 10),}; BubbleSorter. sort (students, Student. compareAge); // input an array of objects and a method address foreach (var student in students) {Console. writeLine (student) ;}}copy the code above to demonstrate the essence of the Delegate, passing the method as a parameter to other methods to increase code flexibility. (It is not clear that the shoes must be carefully used .) 5. There is no difference between using an anonymous method to define a delegate and the previous definition, except that there is a difference when instantiating the delegate. Copy the code class Program {static void Main () {double width = 12; Func <double, double> square = delegate (double length) // here, square is a delegate-type instance {length * = width; return length ;}; Console. writeLine (square (10) ;}the advantage of copying the code anonymous method is that it reduces the code to be written and does not need to define the method used only by the delegate. However, if you need to write the same function in multiple systems using the anonymous method, you are not recommended to use the anonymous method. 6. Lambda expressions C #3.0 supports Lambda expressions and can be used instead of anonymous expressions. For usage, refer to the following example: copy the code // 1. do not obtain any parameter Func <string> f = () => "lining "; // 2. A parameter (can display the specified type or use the type inference) Func <int, string> f1 = (int n) => n. toString (); Func <int, string> f2 = (n) => n. toString (); Func <int, string> f3 = n => n. toString (); // 3. One or more Func <int, int, string> f4 = (int n1, int n2) => (n1 + n2 ). toString (); Func <int, int, string> f5 = (n1, n2) => (n1 + n2 ). toString (); copy the code Lambda to save the writing method, naming method and transfer method process, you can Reduce the amount of code and improve programming efficiency. However, it does not have an advantage in code execution efficiency. In addition, we recommend that you do not abuse lambda expressions, which brings some challenges to debugging and single-step execution. We recommend that you manually write a method for code with more than three lines, which is beneficial for both readability and accessibility of the Code.

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.