1. 程式人生 > >C#自定義事件

C#自定義事件

    class Program
    {

        private int number;
        private delegate void NumberChangedHandle(object sender,object args);
        private event NumberChangedHandle ChangeNumber;
        public Program()
        {
            number = 0;
            ChangeNumber += new NumberChangedHandle(OnChangeNumber);
        }
        public void SetNumber(int value)
        {
            if (number != value)
            {
                Console.WriteLine("SetNumber=>正在將" + number + "更改為" + value);
                number = value;
                if (ChangeNumber != null) ChangeNumber(this, new List<int>() { number,value });//通知事件處理者  ,併發送事件資訊
            }
        }

        public void OnChangeNumber(object sender,object args)
        {
            Console.WriteLine("Tip=>檢測到值已經改變,事件源:" + sender.ToString() + " 引數[0]:" + ((List<int>)args)[0]);//強制轉換取出引數列表
        }
      

        static void Main(string[] args)
        {

            var p = new Program();
            p.SetNumber(5);
            p.SetNumber(15);
          
        }