您的位置:首页 > 编程语言 > C#

C# 事件 订阅与发布

2017-09-04 17:15 246 查看
//服务器
public class Server
{
//服务器发布的事件
public event Action<string> MyEvent;
public void Send(string msg)
{
if (MyEvent != null)
{
Console.WriteLine("Server推送消息:" + msg);
MyEvent(msg);
}
}
}

//客户端
public class Client
{
public Client(Server s)
{
//客户端订阅
s.MyEvent += Receive;
}

public void Receive(string msg)
{
Console.WriteLine("Client收到了通知:" + msg);
}
}


调用:

static void Main()
{
Server s = new Server();
Client c = new Client(s);
s.Send("Hello");

Console.ReadKey();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: