c# - 在 dll 中创建事件并在 Form 中处理事件

标签 c# .net

我使用以下代码创建了一个 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
    }
}

现在我正尝试使用此代码在表单应用程序中处理此 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;
        }
    }
}

我的问题我不确定我哪里出错了。请提出建议。

最佳答案

您需要在事件实际触发之前分配您的事件处理程序,否则代码将抛出NullReferenceException

trigger.CallAlert += new Trigger.AlertEventHandler(trigger_CallAlert);
trigger.isRinging();

此外,建议首先检查是否分配了处理程序:

var handler = CallAlert; // local variable prevents a race condition to occur

if (handler != null) 
{
  handler(this, alertEventArgs);
}

关于c# - 在 dll 中创建事件并在 Form 中处理事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11542189/

相关文章:

c# - 无法从 Process.Start 运行命令

c# - 如何在 C# 中使用 BinaryFormatter 更改反序列化的顺序?

c# - 公共(public)密封类 SqlConnection : DbConnection, ICloneable

.NET 数据提供程序可以快速插入 300,000 条记录吗?

c# - TabControl 未找到 TabControl 项的数据模板

c# - 什么是好的(如果有的话).NET Windows 自动化库?

c# - Swashbuckle/Swagger + ASP.Net 核心 : "Failed to load API definition"

.net - 如何启动一个接受参数并返回值的任务?

c# - Windows 8 : How to undo & redo ink using built in Inking functionality?

c# - myCustomDictionary.Values 应该返回什么类型?