To interpret a delegate in a sentence: a delegate is a type that can store a reference as a function.
Some are similar to the use of the spring framework for interfaces, injecting service objects into the action. The action does not know which service layer to invoke, only the container through the configuration file
When you inject a service object into an action, the action can know which implementation of the serviced Layer object is being invoked.
You pass in the implementation class, and I execute the method that implements the class.
Search the Internet for a description to help understand:
Both delegates and interfaces allow class designers to detach type declarations and implementations. The given interface can be inherited and implemented by any class or struct;
You can create a delegate for a method in any class, provided that the method conforms to the method signature of the delegate. An interface reference or delegate can be used by an object that does not understand the class that implements the interface or delegate method.
The following example is analyzed: First, for a water heater object, he needs to trigger an event (delegate) when he satisfies a certain condition, but the event is less deterministic or not just called a method.
So let's declare a delegate method in this object:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Text;4 namespaceDelegate5 {6 //Water Heaters7 Public classHeater8 {9 Private inttemperature;Ten Public Delegate voidBoilhandler (intparam);//declaring a delegate One Public EventBoilhandler boilevent;//declaring Events A //Boiling Water - Public voidBoilwater () - { the for(inti =0; I <= -; i++) - { -Temperature =i; - if(Temperature > the) + { - if(Boilevent! =NULL) +{//If an object is registered ABoilevent (temperature);//methods to invoke all registered objects at } - } - } - } - } -}
Then, define some methods for handling this event:
1 //Alarm2 Public classAlarm3 {4 Public voidMakealert (intparam)5 {6Console.WriteLine ("Alarm: Beep, the water has been {0} degrees:", param);7 }8}
1 //Display2 Public classDisplay3 {4 Public Static voidShowMsg (intparam)5{//Static Methods6Console.WriteLine ("Display: The water is burning fast, the current temperature: {0} degrees. ", param);7 }8}
All right, all ready, we use the Register event to invoke the methods of these delegates:
1 class Program2 {3 Static voidMain ()4 {5Heater heater =Newheater ();6Alarm Alarm =NewAlarm ();7Heater. Boilevent + = alarm. Makealert;//Registration Method8Heater. Boilevent + = (NewAlarm ()). Makealert;//registering methods for anonymous objects9Heater. Boilevent + = display.showmsg;//registering a static methodTenHeater. Boilwater ();//boil water and automatically invoke the method that registered the object One } A}
The output is:
Alarm: Beep, the water has been 96 degrees:
Alarm: Beep, the water has been 96 degrees:
Display: The water is burning fast, the current temperature: 96 degrees.
C # Delegate Application instance