欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 事件 通过扩展EventArgs 传递数据

程序员文章站 2022-07-13 22:39:59
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    public class IncrementEventArgs : EventArgs
    { 
        public int IncrementCount { get; set; }
    }


    class Incrementer
    {

        public event EventHandler<IncrementEventArgs> CountedDozen;

        public void DoCount()
        {
            IncrementEventArgs args = new IncrementEventArgs();
            for (int i = 1; i < 100; i++)
            {
                if (i % 12 == 0 && CountedDozen != null)
                {
                    args.IncrementCount = i;

                    CountedDozen(this, args);
                }
            }
        
        }

    }

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

        public Dozens(Incrementer incrementer)
        {
            DozensCount = 0;
            incrementer.CountedDozen += IncrementDozensCount;
        }

        private void IncrementDozensCount(object sender, IncrementEventArgs e)
        {
            Console.WriteLine($"Incremented at iteration:{e.IncrementCount}  {sender.ToString()}");


            Console.WriteLine($" DoCount   ---    {DozensCount}");

            DozensCount++;
        }
    }


    class Program
    {


        static void Main(string[] args)
        {
            Incrementer incrementer = new Incrementer();

            Dozens dozens = new Dozens(incrementer);

            incrementer.DoCount();

            Console.Read();


        }
    }
}

 

相关标签: C#知识点