using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 自定义标准事件
{
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber("subscriber",publisher);
Subscriber2 subscriber2 = new Subscriber2("subscriber2", publisher);
//调用引发事件的方法
publisher.DoSomething();
Console.Read();
}
}
/// <summary>
/// 事件的定义和调用,触发事件也可以写在这里面。
/// 系统自带一个委托EventHandler, 可以直接使用
/// </summary>
class Publisher //[发布者]
{
public event EventHandler<CustEventArgs> CustomEvent; //利用系统的委托定义一个事件
public void DoSomething()
{
//调用之前可以在这里写一些其东西
OnCustomEvent(new CustEventArgs("我是事件参数"));
}
/// <summary>
/// 在受保护的虚方法中包装事件的调用,这样就允许派生类重写调用的行为
/// </summary>
/// <param name="e"></param>
protected virtual void OnCustomEvent(CustEventArgs e)
{
CustomEvent?.Invoke(this, e);
}
}
/// <summary>
/// 事件订阅者:事件方法编琯和订阅功能
/// </summary>
class Subscriber
{
/// <summary>
/// 带参构造
/// 订阅的动作写在这里,所以才要传过来发布者
/// </summary>
/// <param name="str"></param>
/// <param name="publisher"></param>
public Subscriber(string str, Publisher publisher)
{
this.Str = str;
//订阅事件
publisher.CustomEvent += HanderCustomEvent;
}
private readonly string Str;
private void HanderCustomEvent(object sender, CustEventArgs e)
{
//
Console.WriteLine($"发布者:{sender.GetType()},订阅者:{Str}, 参数:{e.Message}");
}
}
class Subscriber2
{
/// <summary>
/// 带参构造
/// 订阅的动作写在这里,所以才要传过来发布者
/// </summary>
/// <param name="str"></param>
/// <param name="publisher"></param>
public Subscriber2(string str, Publisher publisher)
{
this.Str = str;
//订阅事件
publisher.CustomEvent += HanderCustomEvent;
}
private readonly string Str;
private void HanderCustomEvent(object sender, CustEventArgs e)
{
//
Console.WriteLine($"发布者:{sender.GetType()},订阅者:{Str}, 参数:{e.Message}");
}
}
public class CustEventArgs : EventArgs
{
public CustEventArgs(string message)
{
this.Message = message;
}
public string Message { get; set; }
}
}