C # monitor variable changes!

Source: Internet
Author: User

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 );

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.