Delegate is an application type that encapsulates a named or anonymous method.
A delegate is used to pass a method as a parameter to another method.
Coding specification for delegates in the. NET Framework:
1 The name of the delegate type should end with EventHandler.
2 The prototype definition of the delegate type: there is a void return value that accepts two parameters: an object, a second EventArgs (or inherits from it)
3 The name of the event is delegated to remove EventHandler remainder
4 the type inheriting from EventHandler should end with EventArgs
C # commissioned interview questions:
1, Hot kettle is responsible for boiling water, when the water temperature is greater than 95 degrees Celsius, alarm alarm, at the same time the display temperature.
2, scalability
3, Low coupling
The code is as follows:
public class Test_delegate11
{
<summary>
Kettle type, responsible for boiling water
</summary>
public class Heater
{
Public readonly string id= "1001"; Additional properties of the kettle
Public readonly string Area= "Jinan, Shandong";
public delegate void Boilheatereventhandler (object sender, Boileventargs e); Defining delegates
public event Boilheatereventhandler Boilheater; Event
<summary>
Parameter class, storage temperature
</summary>
public class Boileventargs:eventargs
{
public int Temp {get; set;}
Public Boileventargs (int i)
{
This. Temp = i;
}
}
public virtual void Onboild (Boileventargs e)
{
if (boilheater!= null)
{
Boilheater (this, e); Execute all methods registered to the event object
}
}
<summary>
Add fire to the water
</summary>
public void Boildwater ()
{
for (int i = m; I <= i++)
{
if (I >= 95)//greater than 95 degrees, start executing the event, the event will be registered with 2 methods (alarm and display)
{
Onboild (New Boileventargs (i));
}
}
}
}
<summary>
Alarm, responsible for Naruto
</summary>
public class Alarm
{
public static void Makealarm (object sender, Heater.boileventargs e)/alarm
{
Heater _heater = (heater) sender;
Console.WriteLine ("Serial number" + _heater.id +) high temperature alarm. ");
}
}
<summary>
Monitor, responsible for displaying current water temperature
</summary>
public class Display
{
public static void Makedisplay (object sender, Heater.boileventargs e)//display
{
Heater _heater = (heater) sender;
Console.WriteLine ("Number" + _heater.id + "Kettle Water temperature:" + e.temp.tostring () + "c \ n");
}
}
public void Main ()//Keynote method, program startup
{
Heater heater = new heater ();
Heater. Boilheater + = Alarm.makealarm; Alarm method of Registered alarm
Heater. Boilheater + = Display.makedisplay; Registering the display method for the display
Heater. Boildwater (); Try to boil the water
}
}
New Test_delegate11 (). Main (); Perform
Results: