1.声明静态事件的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 静态事件
{
public class myClass
{
public static event Action<string> RecieveMessageEvent;
//往用户列表中添加用户
public void AddUser(string user)
{
//收到消息就引发个事件
if (RecieveMessageEvent != null)
{
RecieveMessageEvent(user);
}
}
}
2.添加一窗体,窗体上添加一按钮
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 静态事件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myClass.RecieveMessageEvent += myClass_RecieveMessageEvent;
}
void myClass_RecieveMessageEvent(string obj)
{
MessageBox.Show("触发");
}
private void button1_Click(object sender, EventArgs e)
{
myClass m = new myClass();
m.AddUser("dddd");
}
}
}