天天看點

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 打。