[英]Creating an event in a dll and handling the event in a Form
I have created a DLL using the following code.我使用以下代码创建了一个 DLL。 I have compiled this code as a DLL.我已将此代码编译为 DLL。
namespace DllEventTrigger
{
public class Trigger
{
public delegate void AlertEventHandler(Object sender, AlertEventArgs e);
public Trigger()
{
}
public void isRinging()
{
AlertEventArgs alertEventArgs = new AlertEventArgs();
alertEventArgs.uuiData = "Hello Damn World!!!";
CallAlert(new object(), alertEventArgs);
}
public event AlertEventHandler CallAlert;
}
public class AlertEventArgs : EventArgs
{
#region AlertEventArgs Properties
private string _uui = null;
#endregion
#region Get/Set Properties
public string uuiData
{
get { return _uui; }
set { _uui = value; }
}
#endregion
}
}
Now I'm trying to handle the event triggered by this dll in a forms application with this code.现在我正在尝试使用此代码在表单应用程序中处理此 dll 触发的事件。
namespace DLLTriggerReciever
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Trigger trigger = new Trigger();
trigger.isRinging();
trigger.CallAlert += new Trigger.AlertEventHandler(trigger_CallAlert);
}
void trigger_CallAlert(object sender, AlertEventArgs e)
{
label1.Text = e.uuiData;
}
}
}
My problem i'm not sure where i went wrong.我的问题我不确定我哪里出错了。 Please suggest.请建议。
You need to assign your event handler before the event is actually fired, otherwise the code will throw a NullReferenceException
.您需要在实际触发事件之前分配事件处理程序,否则代码将抛出NullReferenceException
。
trigger.CallAlert += new Trigger.AlertEventHandler(trigger_CallAlert);
trigger.isRinging();
Additionally, it's a recommended practice to check first, whether there are handlers assigned:此外,建议首先检查是否分配了处理程序:
var handler = CallAlert; // local variable prevents a race condition to occur
if (handler != null)
{
handler(this, alertEventArgs);
}
as @Gene said, you need to register the event before raising it.正如@Gene 所说,您需要在引发事件之前注册该事件。 anyway, it's a good practice to check if someone is register to the event you're about to raise by checking for null.无论如何,通过检查 null 来检查是否有人注册了您将要引发的事件是一个很好的做法。
like this:像这样:
if (this.CallAlert != null)
this.CallAlert(new object(), alertEventArgs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.