看懂 ,学会 .NET 事件的正确姿势-简单版

时间:2023-03-09 00:40:01
看懂 ,学会 .NET 事件的正确姿势-简单版
using System;
namespace EventTest
{
public class EventDemo
{
public void EventTest()
{
Cat cat = new Cat();
MouseEventArgs ms = new MouseEventArgs();
MasterEventArgs mas = new MasterEventArgs();
cat.Calling += ms.Escape;//老鼠对 clling 订阅
cat.Calling += mas.Wakened;//人 对 calling 订阅
cat.Call(); //猫叫
}
}
public sealed class Cat
{
public event EventHandler Calling;
public void Call()
{
Console.WriteLine("猫叫了...");
Calling?.Invoke(this, EventArgs.Empty);
}
}
public sealed class MouseEventArgs : EventArgs
{
public void Escape(object sender, EventArgs e)
{
Console.WriteLine("老鼠逃跑了...");
}
}
public sealed class MasterEventArgs : EventArgs
{
public void Wakened(object sender, EventArgs e)
{
Console.WriteLine("主人醒了");
}
}
}