C # basics-Use of delegation

Source: Internet
Author: User

C # basics-Use of delegation
1. What is a delegate is a type that defines the method signature. When a delegate is instantiated, You can associate its instance with any method with a signature compatibility. You can call a method by entrusting an instance. A delegate is a reference type, so it has the connectivity of the reference type. It saves not actual values, but references to objects stored in managed heap. The delegate can reference static and non-static methods. In general, delegation can be A simple constraint, for example, I declare A principal A and A can accept two parameters at the same time (human resources, logistics and official services) at work, so long as someone wants to handle (human resources, logistics), they can register with principal A, and A can accept these methods and then handle them. 2. delegate Declaration the delegate can be declared through delegate. The delegate can depend on a class or a namespace. That is, declarations in the class and outside the class. Among them, delegate can have the return type and non-return type. Among them, delegate also supports the generic type. Public delegate double AddNum (double num1, double num2); public delegate void ShowMsg (string str); 3: Use of delegation 1. basic usage: The following is a calculation method. It declares a delegate CalculatorDelegate, and then registers the AddNum and SumNum methods in the Main method, the registered method must be consistent with the delegate parameter and return type. Otherwise, the system will prompt the [Delegate and registration method do not match] This is a direct compilation failure. If a delegate is registered with multiple methods, it is called multicast. For multicast, after the delegate is called, it is executed in the registration order. However, for methods with returned values, the returned values after the last registered method is executed are returned. Notes: when registering a method for the first time, you can use [= Registration] or [new CalculatorDelegate (method name)], and use [+] to add a method later ], to cancel the registration, use [-] to run the code and run the result, for example, copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace using gebobcoder. delegate {public delegate double CalculatorDelegate (double num1, double num2); // Delegate, declare public class Program {public static double AddNum (double num1, double num2) {Console. writeLine ("Sum = {0}", num1 + num2); return num1 + num2;} public static double SubNum (double num1, double num2) {Console. writeLine ("Sub = {0}", num1-num2); return num1-num2;} public static void Main (string [] args) {CalculatorDelegate calculatorDel = AddNum; // currently, This is the unicast Console. writeLine ("delegate the result of a method: {0}", calculatorDel (1, 2); calculatorDel + = SubNum; // currently the multicast Console. writeLine ("delegate two methods The result is: {0} ", calculatorDel (1, 2); Console. readKey () ;}} copy Code 2. several methods of delegated registration: In addition to the preceding method, the delegate registration method also supports the Linq method and anonymous method. In fact, a lot of delegation is also performed in Linq, such as using List <T>. where (), List <T>. the sort () method actually uses a lot of delegation. It can be understood as the epitome of delegation. Copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace using gebobcoder. delegate {public delegate double CalculatorDelegate (double num1, double num2); // delegate public class Program {public static void Main (string [] args) {CalculatorDelegate calculatorDel = Delegate (double x, double y) // equivalent to the AddNum method {return x + y;}; Console. write Line ("result of delegate a method: {0}", calculatorDel (1, 2); calculatorDel + = (x, y) ==/// equivalent to the SumNum method {return x-y ;}; Console. writeLine ("result of delegate two methods: {0}", calculatorDel (1, 2); Console. readKey () ;}} copy code 3. small addition: in fact.. net Framework provides built-in delegation. action <T>, Func <T, out Result>. Action is a non-return value generic delegate, and Func is a generic delegate with a returned value [out Result is the returned value, but it is not required to input an out parameter when used. For Action <T, T, out Result> is actually two parameters.] The Code is as follows: Notes: note that Func <> there are only two AddNum parameters. In fact, the third parameter is the corresponding return value. This is different from the delegate we mentioned earlier. copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace using gebobcoder. delegate {public class Program {private static void ShowMsg (string str) {Console. writeLine (str);} private static double AddNum (double num1, double num2) {return num1 + num2;} public Static void Main (string [] args) {Action <string> action = ShowMsg; action ("Action delegate easy to use! "); Func <double, double, double> func = AddNum; // Notes Console. writeLine ("Func delegate is really useful, sum of two numbers: {0}", func (1, 2); Console. readKey () ;}} copy code 4: Conclusion: due to the recent access to Silverlight, events will be continuously accessed after delegation. So I read the event Delegate knowledge and wrote a blog record over the past two days. If you have any incorrect understanding or incorrect description, please kindly advise. The next section updates the usage of events.

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.