1.直接使用delegate
不废话,直接上代码
namespace DelegateEventTest
{
class Program
{
static void Main(string[] args)
{
//模拟场景,主人通知宠物们来吃饭了,宠物们收到消息
Master m1 = new Master();
// 多播委托
m1.NofifyDelegateHandler += (new Cat()).Receive;
m1.NofifyDelegateHandler += (new Dog()).Receive;
m1.notify("吃饭了");
}
}
/// <summary>
/// 主人类
/// </summary>
public class Master
{
// 委托
public delegate void NotifyDelegate(string message);
// 事件:可以理解是带event关键字的委托的实例
public event NotifyDelegate NofifyDelegateHandler;
// 一个普通方法,当实例调用改方法时, 会去调用事件
public void notify(string message)
{
Console.WriteLine($"我是{this.GetType().Name}, 通知:{message}");
if (this.NofifyDelegateHandler != null)
{
this.NofifyDelegateHandler(message);
}
}
}
// 定义一个接受消息的接口
public interface IReceiveMessage
{
void Receive(string message);
}
// 猫咪类
public class Cat : IReceiveMessage
{
public void Receive(string message)
{
Console.WriteLine($"我是{this.GetType().Name},收到信息:{message}, 喵喵喵");
}
}
// 狗狗类
public class Dog : IReceiveMessage
{
public void Receive(string message)
{
Console.WriteLine($"我是{this.GetType().Name},收到信息:{message}, 汪汪汪");
}
}
}
运行结果
image.png
2.使用Action
namespace DelegateEventTest
{
class Program
{
static void Main(string[] args)
{
//模拟场景,主人通知宠物们来吃饭了,宠物们收到消息
Master m1 = new Master();
m1.NotifyAction += ((new Cat()).Receive);
m1.NotifyAction += (new Dog()).Receive;
m1.notify2("吃饭了");
}
}
/// <summary>
/// 主人类
/// </summary>
public class Master
{
public event Action<string> NotifyAction;
public void notify2(string message)
{
Console.WriteLine($"我是{this.GetType().Name}, 通知:{message}");
NotifyAction(message);
}
}
// 定义一个接受消息的接口
public interface IReceiveMessage
{
void Receive(string message);
}
// 猫咪类
public class Cat : IReceiveMessage
{
public void Receive(string message)
{
Console.WriteLine($"我是{this.GetType().Name},收到信息:{message}, 喵喵喵");
}
}
// 狗狗类
public class Dog : IReceiveMessage
{
public void Receive(string message)
{
Console.WriteLine($"我是{this.GetType().Name},收到信息:{message}, 汪汪汪");
}
}
}
结果一样
image.png
网友评论