C#使⽤事件实现发布订阅模式C# 使⽤事件实现发布订阅模式
我们假设⼀个简单的场景:
皮虫发布者有⼀个数字,这个数字可能会改变
订阅者希望每次当发布者的数字改变时,⾃⼰都要收到消息古诗幼儿
寒假英语如何实现代码呢?
1.定义发布者类
// 发布者,当数字改变时会发布⼀个NumberChange事件
class Publisher
{
public delegate void NumberChangeDelegate(int newValue);
public event NumberChangeDelegate NumberChange;
王小波的全部作品
private int myNumber;
public int MyNumber
{
get { return myNumber; }
t
{
if (value != MyNumber)
{
myNumber = value;
NumberChange(value);
}
}
}
}
2.定义订阅者类
// 订阅者,当收到发布者的NumberChange事件时执⾏⼀些操作
class Subscriber
{
public void OnNumberChange(int newValue)
{
Console.WriteLine("Number is changed to " + newValue);
豆豉做法}
}
3.Main函数
public static void Main(string[] args)
{
// 创建⼀个发布者
Publisher publisher = new Publisher();
// 创建第⼀个订阅者并订阅发布者的NumberChange事件
Subscriber subscriber = new Subscriber();
publisher.NumberChange += subscriber.OnNumberChange;
// 创建第⼆个订阅者并订阅发布者的NumberChange事件
Subscriber subscriber2 = new Subscriber();
publisher.NumberChange += subscriber2.OnNumberChange;
publisher.MyNumber = 1;
publisher.MyNumber = 2;
}
完整代码
using System;
namespace TestEvent
{
// 发布者,当数字改变时会发布⼀个NumberChange事件
class Publisher
{
public delegate void NumberChangeDelegate(int newValue); public event NumberChangeDelegate NumberChange;
private int myNumber;
public int MyNumber
{
get { return myNumber; }
t
{
if (value != MyNumber)
{
myNumber = value;
NumberChange(value);
}
}
}
}
// 订阅者,当收到发布者的NumberChange事件时执⾏⼀些操作 class Subscriber
{
public void OnNumberChange(int newValue)
{
Console.WriteLine("Number is changed to " + newValue);
芝麻团}
}
明天会更好吉他谱
class Program
{
public static void Main(string[] args)
{
// 创建⼀个发布者
Publisher publisher = new Publisher();
// 创建第⼀个订阅者并订阅发布者的NumberChange事件
Subscriber subscriber = new Subscriber();
publisher.NumberChange += subscriber.OnNumberChange;
精开头的成语
// 创建第⼆个订阅者并订阅发布者的NumberChange事件
Subscriber subscriber2 = new Subscriber();
publisher.NumberChange += subscriber2.OnNumberChange;
publisher.MyNumber = 1;
publisher.MyNumber = 2;
}
}
}
运⾏结果:
Number is changed to 1
Number is changed to 1
Number is changed to 2
Number is changed to 2