您现在的位置:首页 > >

委托 + 事件 = 发布订阅

发布时间:

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

namespace SubscribeDemo
{
delegate void Handler(); //委托类型声明

class Incrementer
{
public event Handler CountedADozen; //创建注册事件并发布

public void DoCount()
{
for (int i = 1; i < 100; i++)
{
if (i % 12 == 0 && CountedADozen != null)
{
CountedADozen(); //每增加12个计数触发委托的事件一次
}
}
}
}

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

public Dozens(Incrementer incrementer)
{
DozensCount = 0;
incrementer.CountedADozen += IncrementDozensCount; //订阅事件
}

void IncrementDozensCount()
{
DozensCount++; //申明事件处理程序
}
}

class Program
{
static void Main(string[] args)
{
Incrementer incrementer = new Incrementer();
Dozens dozensCounter = new Dozens(incrementer); //触发订阅事件
incrementer.DoCount();

Console.WriteLine("Number of dozens = {0}",dozensCounter.DozensCount);
Console.ReadKey();
}
}
}

?



转载于:https://www.cnblogs.com/HansZimmer/p/11344188.html


热文推荐
猜你喜欢
友情链接: