c# - 如何通知所有订阅者类关于一个类中引发的事件?
问题描述
我正在学习如何使用类周围的事件来通知 2 个类,如果一个类中发生偶数。我创建了以下内容。
namespace TestConsole
{
class Program : Form
{
public event EventHandler Something;
public Program()
{
Button btn = new Button();
btn.Parent = this;
btn.Text = "Click Me.!";
btn.Location = new Point(100, 100);
btn.Click += Btn_Click;
Something += HandleThis;
}
private void Btn_Click(object sender, EventArgs e)
{
Something(this,null);
}
private void HandleThis(object sender, EventArgs e)
{
Console.WriteLine("From Main: Something typed");
}
static void Main(string[] args)
{
Application.Run(new Program());
Console.ReadLine();
}
}
class One
{
One()
{
Program SubscriberObj = new Program();
SubscriberObj.Something += HandleEvent;
}
private void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("From One: Something typed");
}
}
class Two
{
Two()
{
Program SubscriberObj = new Program();
SubscriberObj.Something += HandleEvent;
}
private void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("From Two: Something typed");
}
}
}
我希望在单击按钮后触发第一类和第二类的 HandleEvent 方法。但我只看到在 Program 课程中引发的事件。如何做到这一点?
解决方案
You do not create an instance of One
and Two
. Therefore, no class will register for this event. Also, you create new instances of program
in One
and Two
. But you need the same instance in which the event is fired. You must pass the instance of program
in the constructor. You should also always check if the handler is null when the event gets fired.
EventHandler handler = Something;
handler?.Invoke(this, new EventArgs());
This code is equivalent to:
EventHandler handler = Something;
if (handler != null)
{
handler.Invoke(this, new EventArgs());
}
推荐阅读
- c# - 基类中的 Specflow beforeScenario 调用多次,套件中的每个功能调用一次
- excel - 通过引用文件路径在用户表单中设置图像控件的值
- vba - google people.api, people.getBatchGet,如何建立resourceNames List?
- php - 获取 JSON 对象时出错“尝试获取非对象的属性”
- amazon-web-services - Beanstalk .ebextensions 错误 - 模板的资源块中未解决的资源依赖关系
- javascript - 我正在使用 vuetify 获得一个 v-on 处理程序 handler.apply 不是 vue 工具栏中的函数错误
- javascript - 需要很好的例子:templateShareable=true 什么时候有用?
- hibernate - Hibernate 版本列名异常
- ruby-on-rails - 在 Rails 中下载和重定向
- linux - libs 路径“/run/opengl-driver”如何注入到像 compton 这样的 Nix 二进制文件中