C # when implementing a property value change trigger event

In the software industry we do, we often encounter real-time monitoring to a certain point, to do some things at this point when changes

Into the program where it is to monitor the real-time value of a property, a trigger event occurs when the value changes, its core is to make use of the property Set method to determine the value of the current set is equal to the original value, if equal direct assignment ignored, if not equal, indicating that the value has changed, according to his own method invocation, declare a delegate, event trigger method

Core code :

public delegate void tempChange(object sender,EventArgs e);
public event tempChange onTempChange;

private bool _temp= false;
public bool Temp
{
            get { return _temp; }
            set
            {
                if (_temp!=value)
                {
                    onTempChange(new object(), new EventArgs());
                }
                _temp= value; 
       }
}

Below we do a Demo, to test

We create a from, top to add a lable, we add a button to change the value of this property by temp button, so that it triggers a corresponding event

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int i = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            changeEvent += Form1_changeEvent;
        }

        void Form1_changeEvent(string value)
        {
            this.richTextBox1.Invoke(new Action(() => { this.richTextBox1.AppendText("当前lable的值为" + value+"\r\n"); }));
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Temp = i + "";
            label1.Text = Temp;
            i++;
        }

        public delegate void ChangeDelegate(string value);
        public event ChangeDelegate changeEvent;

        public string _temp;
        public string Temp
        {
            get { return _temp; }
            set
            {
                if (_temp != value)
                {
                    changeEvent(value);
                }
                _temp = value;
            }
        }
    }
}

test:

We can see every click of a button changes the value of all temp, thereby triggering the event ------ changeEvent add text to richTextBox

 

Guess you like

Origin www.cnblogs.com/pandefu/p/11204310.html