In the previous blog briefly introduced the basic knowledge of the delegation, in this article will introduce the relationship between the delegate and the event.
The origin of the incident
We can see that in the implementation of the callback using the delegate, we often need to define a delegate object and an externally accessible method to add the delegate, which makes us feel more cumbersome. C # provides the event keyword to ease the burden of direct use of delegates, and the compiler automatically provides registration, cancellation methods, and delegates to the necessary members. First let's look at the steps to define the event:
1. Define the delegate type first;
2. Events of the delegate type are determined by the event keyword.
public delegate int Caculate(int x, int y);
public event Caculate OnCaculate;
See what the compiler defines for us.
First we can see a Caculate object defined for us, followed by a definition of two methods Add_oncaculate and Remove_oncaculate. We can look at some of the core things in the Add_oncaculate two methods. Add_oncaculate:
IL_0008: call
class [mscorlib]System.Delegate [mscorlib] System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
It is obvious that the Add_oncaculate method calls the Combine method of the delegate, so we can also think of the Remove method that the Remove_oncaculate method calls. From the above we can see in fact that the event keyword just provides us with a grammatical convenience.
A slightly complete example
This example refers to the "C # and. NET3.0 Advanced Program Design" above. Using car for example, when the vehicle accelerates to a certain limit will trigger an alert event, when more than a certain speed will trigger a car bombing event. First look at the delegates and events:
public delegate void CarEventHandler(string msg);
public event CarEventHandler AbortToBlow;
public event CarEventHandler Exploded;
There are two events in the Eventcar class, one is Aborttoblow and the other is exploded. The following are several properties and fields for car:
private const int MaxSpeed = 180;
public int CurrSpeed { get; private set; }
public bool IsDead { get; private set; }
public string Name { get; private set; }