最近一直在研究委托与事件,下面是我的个人理解
1 class BoliEventAgrs : EventArgs//继承系统事件参数接口 2 { 3 public readonly int tem; 4 public BoliEventAgrs(int tem) 5 { 6 this.tem = tem; 7 } 8 }
//注册 boli.BoliWaterEvent += boli1.Alarm; boli.BoliWaterEvent += boli1.Alarm1;
//执行
boli.Boliwater();
4。效果

5.下面是完整代码
using System;
namespace DelegateEventObserver
{
class Program
{
static void Main(string[] args)
{
a boli = new a();
b boli1 = new b();
boli.BoliWaterEvent += boli1.Alarm;
boli.BoliWaterEvent += boli1.Alarm1;
boli.Boliwater();
Console.ReadKey();
}
}
class BoliEventAgrs : EventArgs//继承系统事件参数接口
{
public readonly int tem;
public BoliEventAgrs(int tem)
{
this.tem = tem;
}
}
class a
{
//public delegate void Boli(object sender,BoliEventAgrs e);
public event EventHandler<BoliEventAgrs> BoliWaterEvent;//BoliEventAgrs 为委托参数
public void Boliwater()
{
for (int i=0; i<100;i++)
{
if (i>90)
{
BoliEventAgrs e = new BoliEventAgrs(i);
if (BoliWaterEvent != null)
{
BoliWaterEvent(this, e);
}
}
}
}
}
/// <summary>
/// 委托方法,事件注册方法,参数e为 控制温度
/// </summary>
class b
{
public void Alarm(object sender,BoliEventAgrs e)
{
if (e.tem>95)
{
Console.WriteLine("水温{0}",e.tem);
}
}
public void Alarm1(object sender, BoliEventAgrs e)
{
if (e.tem >98)
{
Console.WriteLine("水温{0},马上开啦", e.tem);
}
}
}
}
原文:https://www.cnblogs.com/Maxs/p/9158521.html