c# - 如何在 C# 中正确触发事件
问题描述
单击按钮时,我试图触发一个事件。我单击按钮,没有任何反应。
问题是我总是得到 null ,如下EventA
所示OnEventA()
:
namespace eventsC
{
public partial class Form1 : Form
{
public event EventHandler EventA;
protected void OnEventA()
{
if (EventA != null)
//never arrives here as EventA is always = null
EventA(this, EventArgs.Empty);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OnEventA();
}
}
}
编辑:
基于来自 Henk Holterman 的链接,我还测试了这段代码:
public delegate void Eventhandler(object sender, Eventargs args);
// your publishing class
class Foo
{
public event EventHandler Changed; // the Event
protected virtual void OnChanged() // the Trigger method, called to raise the event
{
// make a copy to be more thread-safe
EventHandler handler = Changed;
if (handler != null)
{
// invoke the subscribed event-handler(s)
handler(this, EventArgs.Empty);
}
}
// an example of raising the event
void SomeMethod()
{
if (...) // on some condition
OnChanged(); // raise the event
}
}
当我点击一个按钮时我会打电话OnChanged()
,但结果仍然是一样的:EventA = null
.
解决方案
我以这种方式解决了我的问题:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace eventsC
{
public partial class Form1 : Form
{
public static event EventHandler<EventArgs> myEvent;
protected void OnMyEvent()
{
if (myEvent != null)
myEvent(this, EventArgs.Empty);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myEvent += Handler;
//call all methods that have been added to the event
myEvent(this, EventArgs.Empty);
}
private void button1_Click(object sender, EventArgs e)
{
OnMyEvent();
}
static void Handler(object sender, EventArgs args)
{
Console.WriteLine("Event Handled!");
}
}
}
推荐阅读
- avr - AVR 工作室错误“得到 0xc0,预期为 0x00”
- swift - 如何在 iOS 12 的导航栏下扩展滚动视图顶部?
- postgresql - 将 Postgresql 数组导入 Solr 字段
- spring-cloud-dataflow - ETL 的 Spring Cloud 数据流
- cocoapods - 创建基于Metal.framework的pod库,metal shader报错:metal_stdlib not found
- javascript - 如何从一个数组中获取代码并从另一个数组中查找值并返回新值
- docker - Kubernetes - 在命名空间和服务之间进行通信
- android - 如何创建圆角六边形?
- angularjs - 禁用单击选项卡。想要通过点击标签来停止切换标签
- ios - Interface Builder 以级联方式显示所有@IBInspectable