In practical applications, a monitoring mechanism is usually required. The most common method is the chick method of a button. In vs2005, the monitoring of controls has been defined for us. We only need to write code in the method. But what if I encounter a variable?
First, initialize the simplest variable.
Private int myvalue = 0;
Public int myvalue
{
Get {return myvalue ;}
Set
{
// If the assigned value is different from the original value
If (value! = Myvalue)
{
// This event is triggered!
Whenmyvaluechange ();
}
// Assign a value!
Myvalue = value;
}
}
// Trigger the event
Private void whenmyvaluechange ()
{
???
}
You may think it is okay, but it is not. In this way, the value of myvalue is assigned only after the trigger event is executed. This means that when you execute this trigger event, you will find that the original variable has not changed, which will lead to unexpected errors. Therefore, the whenmyvaluechange () action cannot be directly written. Instead, it should be used to trigger another method, which will be performed independently without affecting the value assignment of myvalue. This is triggered when the variable value changes.
Now I want to define another method body:
// Triggered when the variable is changed
Private void aftermyvaluechanged ()
{
// Do something
}
So how can we use whenmyvaluechange () to trigger aftermyvaluechanged () and make aftermyvaluechanged () Independent?
// Define a delegate
Public Delegate void myvaluechanged (Object sender, eventargs E );
// Events associated with Delegation
Public event myvaluechanged onmyvaluechanged;
// Bind the aftermyvaluechanged Delegate to the event
Onmyvaluechanged + = new myvaluechanged (aftermyvaluechanged );
// Trigger this event in whenmyvaluechange.
Private void whenmyvaluechange ()
{
If (onmyvaluechanged! = NULL)
{
Onmyvaluechanged (this, null );
}
}