回覆列表
  • 1 # 使用者834195712159

    程式碼示例:

    public class Program {

    //需要監控的欄位

    private int myValue;

    //屬性設定,此處呼叫了事件觸發函式

    public int MyValue{

    get { return myValue; }

    set{

    //如果變數改變則呼叫事件觸發函式

    if (value!=myValue) {

    WhenMyValueChange();

    }

    myValue = value;

    }

    }

    //定義的委託

    public delegate void MyValueChanged(object sender, EventArgs e);

    //與委託相關聯的事件

    public event MyValueChanged OnMyValueChanged;

    //建構函式初始化初值並繫結一個事件處理函式

    public Program(){

    myValue = 0;

    OnMyValueChanged += new MyValueChanged(afterMyValueChanged);

    }

    //事件處理函式,在這裡新增變數改變之後的操作

    private void afterMyValueChanged(object sender, EventArgs e) {

    //do something

    }

    //事件觸發函式

    private void WhenMyValueChange(){

    if (OnMyValueChanged != null) {

    OnMyValueChanged(this, null);

    }

    }

    }

    可以將要監控的變數寫成一個類

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    namespace WindowsFormsApplication7 {

    class MyClass {

    private int myValue;

    public int MyValue{

    get { return myValue; }

    set {

    if (value !=myValue ){

    WhenMyValueChange();

    }

    myValue = value;

    }

    }

    //定義的委託

    public delegate void MyValueChanged(object sender, EventArgs e);

    //與委託相關聯的事件

    public event MyValueChanged OnMyValueChanged;

    //事件觸發函式

    private void WhenMyValueChange() {

    if(OnMyValueChanged !=null ){

    OnMyValueChanged(this, null);

    }

    }

    }

    }

    該類應用的程式碼

    namespace WindowsFormsApplication7{

    public partial class Form1 : Form {

    MyClass myclase;

    public Form1(){

    InitializeComponent();

    myclase = new MyClass();

    myclase.MyValue = 23;

    myclase.OnMyValueChanged += myclase_OnMyValueChanged;

    myclase.MyValue = 24;

    }

    void myclase_OnMyValueChanged(object sender, EventArgs e){

    MessageBox.Show("gaibian");

    }

    private void Form1_Load(object sender, EventArgs e) {

    }

    }

    }

  • 中秋節和大豐收的關聯?
  • 諾基亞E52和E66哪個好?