一、事件广播(一个事件发布者,多个订阅者)
参考
https://www.runoob.com/csharp/csharp-event.html
https://www.cnblogs.com/gq0324/p/8177799.html
https://www.cnblogs.com/MuNet/p/8544954.html
#region 事件(一个事件发布者,多个订阅者)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace QueueSample
{
/***********发布器类***********/
public class EventTest
{
private int value;
public delegate void NumManipulationHandler();
public event NumManipulationHandler ChangeNum;
protected virtual void OnNumChanged()
{
if (ChangeNum != null)
{
ChangeNum(); /* 事件被触发 */
}
else
{
Console.WriteLine("event not fire");
}
}
public EventTest()
{
string str= null;
SetValue(str);
}
public void SetValue(string str)
{
if (str != null && str == "触发所有事件")
{
OnNumChanged();
}
}
}
/***********订阅器类***********/
public class subscribEvent1
{
public void printf1()
{
Console.WriteLine("event fire111111");
//Console.ReadKey(); /* 回车继续 */
}
}
public class subscribEvent2
{
public void printf2()
{
Console.WriteLine("event fire2222222");
//Console.ReadKey(); /* 回车继续 */
}
}
public class subscribEvent3
{
public void printf3()
{
Console.WriteLine("event fire3333333");
//Console.ReadKey(); /* 回车继续 */
}
}
/***********触发***********/
class Program
{
static void Main(string[] args)
{
EventTest e = new EventTest(); //实例化事件发布者
subscribEvent1 v1 = new subscribEvent1(); //实例化事件订阅者1
subscribEvent2 v2 = new subscribEvent2(); //实例化事件订阅者2
subscribEvent3 v3 = new subscribEvent3(); //实例化事件订阅者3
e.ChangeNum += new EventTest.NumManipulationHandler(v1.printf1); //订阅事件或者说是注册事件
e.ChangeNum += new EventTest.NumManipulationHandler(v2.printf2); //订阅事件或者说是注册事件
e.ChangeNum += new EventTest.NumManipulationHandler(v3.printf3); //订阅事件或者说是注册事件
e.SetValue("触发所有事件");//引发事件或者说是触发事件
Console.ReadLine();
}
}
}
#endregion
控制台输出结果:
event fire111111
event fire2222222
event fire3333333