天天看点

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