using System;using System.IO;using System.Text.Encodings.Web;using System.Text.Json;using System.Text.Unicode;using System.Transactions;namespace ConsoleApp9{ internal class Program { private static void Main(string[] args) { //发布消息
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Transactions;
namespace ConsoleApp9
{
internal class Program
{
private static void Main(string[] args)
{
//发布消息
publish _publish = new publish();
//接收消息
Receive _receive = new Receive();
_publish.testEvent += _receive.ReceviveMsg;
_publish.publishMsg();
}
}
//定义一个传入一个参数委托 (委托和类一样可以直接定义在命名空间下)
public delegate string testDelegate(string msg);
//这个地方也可以不定义委托直接使用 EventHandler(如下exampleEvent事件) 来定义事件传入类型即可
public class publish
{
//定义一个事件使用上面定义的委托
public event testDelegate testEvent;
public event EventHandler<string> exampleEvent;
//调用事件传入消息
public void publishMsg()
{
//这样调用必须要在定义这个事件的类的内部调用 其他调用都必须是 += 或者 -= 的形式
testEvent("有内鬼!");
}
}
public class Receive
{
public string ReceviveMsg(string msg)
{
Console.WriteLine($"接收到消息:{msg}");
Console.ReadLine();
return $"接收到消息:{msg}";
}
}
}