If you want to define an event in C #, first you create a delegate (delegate) and use it to define a label for the event you want to use, and then you can use the Event keyword to define an event on the basis of that delegation.
Two points to note is: First, you have to create a delegation, and secondly, according to the delegation you created to define an event, this is a complete event definition.
Let's say we've enhanced the product class in the book. Added a namechanged event that occurs only if name is changed through the property channel. This event does not occur if the private variable name is modified through the internal code of the class. The code is as follows:
public class Product
{
public delegate void Namechangedeventhandler ();//define Event
The call to the public event Namechangedeventhandler namechanged;//event namechanged
public string Name
{
Get{return name;}
Set{name = value;
if (namechanged!= null)
{
Namechanged ();
}
}
}
}
The initialization function product (parameter 1, parameter 2) in the previous lesson cannot raise an event because the name at this time is internally modified, so the event does not occur when the object is instantiated, but when the object's Name property is passed Saleproduct.name = When "ABCDEFG" is changed, an event is raised.
Here we can see that when the event occurs, no actual code has been executed, to handle the event, you have to create a subroutine that corresponds to this event, which contains the sequence of actions to be processed when an event occurs, and then connects the subroutine to the event. To control the product class, You need to define an event hook in another class. This event hook has the same syntax as the event (event), for example, in the product class there is no return parameter or parameter, so the event hook is consistent with the following form: Handler
public void changedetected ()
{//The code here is the code to be processed when the event occurs}
The next step is to hook the event hook to the event, first do a delegate point to the event hook, and then use the + = symbol to attach the delegate to the event: the code is as follows:
Product saleproduct = new product ();
Saleproduct.namechanged + = new Namechangedeventhandler (changedetected);
Now, when saleproduct.name = "Kitchen garbage" executes, the event occurs, and the specific action that occurs is written in changedetected ().
I hope I've made it clear that this is a very difficult thing to understand. Ah, I can figure out how it is a thing, the next article is ready to find an online article on the event processing to understand, if the understanding is no problem, then I really understand, everyone if there is nothing to understand the place can give me a message, message will be complex