C# 標准事件的用法包含參數傳遞


使用 EventHandler<> 委托來實現標准事件,通過 EventArgs 傳遞事件參數,其本身不能傳遞任何參數,需要被繼承。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LianXiStandEvent
{
    class Program
    {
        static void Main(string[] args)
        {
            Incrementer incrementer = new Incrementer();
            Dozens dozens = new Dozens(incrementer);

            incrementer.DoCount();
            Console.WriteLine("總共有打包:{0} 打。", dozens.DozensCount);

            Console.ReadKey();
        }
    }

    // 標准事件傳遞的參數
    public class IncrementeEventArgs : EventArgs
    {
        public int IterationCount { get; set; }
    }

    public class Incrementer
    {
        public event EventHandler<IncrementeEventArgs> CountADozen = null;

        public void DoCount()
        {
            IncrementeEventArgs args = new IncrementeEventArgs();

            for (int i = 1; i < 100; i++)
            {
                if (i % 12 == 0 && CountADozen != null)
                {
                    args.IterationCount = i;
                    CountADozen(this, args); // 觸發事件,傳遞參數
                }
            }
        }
    }

    public class Dozens
    {
        public int DozensCount { get; set; }

        public Dozens(Incrementer incrementer)
        {
            DozensCount = 0;
            incrementer.CountADozen += Incrementer_CountADozen;
        }

        private void Incrementer_CountADozen(object sender, IncrementeEventArgs e)
        {
            Console.WriteLine("在迭代 {0} 處打包,事件發送者是 {1}", e.IterationCount, sender.ToString());
            DozensCount++;
        }
    }
}

運行:

在迭代 12 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 24 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 36 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 48 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 60 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 72 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 84 處打包,事件發送者是 LianXiStandEvent.Incrementer
在迭代 96 處打包,事件發送者是 LianXiStandEvent.Incrementer
總共有打包:8 打。



參考: 《WPF 圖解教程 第4版》—— P263


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM