C#中的委托和事件

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

namespace Study_05_Observer设计模式
{
    // 计数器
    public class Counter
    {
        int x;
        int y;
        //声明委托
         public delegate void CountEventHandler(object sender, CountEventArgs e);
        public event CountEventHandler Counted;
        // 为Observer传递感兴趣的参数
         public class CountEventArgs : EventArgs
        {
            public readonly int x;
            public readonly int y;
            public CountEventArgs(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }
        // 调用此函数,就会通知Observer,Observer会执行注册进Counted事件的方法
         protected virtual void OnCounted(CountEventArgs e)
        {
            if (Counted != null)
                Counted(this, e);
        }
        public void Count()
        {
            for (int m = 0; m < 21; ++m)
            {
                y = m;
                for (int n = 0; n < 21; ++n)
                {
                    x = n;
                    CountEventArgs e = new CountEventArgs(x, y);
                    OnCounted(e);
                }
                Console.WriteLine();
            }
        }
    }
    
    // 绘图器
    public delegate bool Condition(int x, int y); // 绘图条件
    public class Drawer
    {
        public event Condition condition;
        public Drawer(Condition condition) { this.condition = condition; }
        public void DrawType(object sender, EventArgs e)
        {
            Counter.CountEventArgs args = e as Counter.CountEventArgs;
            if (condition(args.x,args.y))
                Console.Write("0");
            else
                Console.Write(" ");
        }
    }

    class Program
    {
        static bool Condition_1(int x, int y)
        {
            if (Math.Pow(x - 10, 2) + Math.Pow(y - 10, 2) < 80)
                return false;
            else
                return true;
        }

        static void Main(string[] args)
        {
            Drawer drawer = new Drawer(Condition_1);
            Counter counter = new Counter();
            counter.Counted += drawer.DrawType;
            counter.Count();
            Console.ReadKey();
        }
    }
}

本例中Counter差数器遍历x,y坐标,Drawer负责按条件进行绘图。首先初始化Drawer,添加条件。把画图功能注册入查数器查数事件,每次查数时触发画图。

原文地址:https://www.cnblogs.com/cheetahw/p/2719649.html