一个类如果声明一个Public的委托让其他方法注册,同样也会存在外部直接调用此委托,这样是有会出现莫名的调用风险的。因此就有了事件,事件无法在外部直接调用。外部只有注册(定阅)。内部进行发布。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 事件_观察者模式_
{
class Program
{
static void Main(string[] args)
{
CAT cat = new CAT("TOM","黄色");
Mouse mouse1 = new Mouse("米奇1", "黑1色",cat);
Mouse mouse2 = new Mouse("米奇2", "黑2色", cat);
Mouse mouse3 = new Mouse("米奇3", "黑3色", cat);
cat.CatComing();
// cat.CatCome();这如果不是一个事件,是可以在外面调用的,是事件则不能调用。
Console.ReadKey();
}
}
}
class CAT
{
public string name;
public string color;
public CAT(string name,string color)
{
this.name = name;
this.color = color;
}
public void CatComing()
{
Console.WriteLine(color+"的"+name+"进来了!");
CatCome();
}
public event Action CatCome;//这代表示这个CAT类中的事件发布
}
}
class Mouse
{
public string name;
public string color;
public Mouse(string name,string color,CAT cat)
{
this.name = name;
this.color = color;
cat.CatCome += RunAway;//这表示Mouse类中定阅cat.CatCome(也就是将RunAway()注册到CAT类中的cat.CatCome事件中),
}
public void RunAway()
{
Console.WriteLine(color+"的"+name+"跑了!");
}
来源:https://www.cnblogs.com/trlq/p/7173174.html