首页 > 解决方案 > 如何在 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.

标签: c#

解决方案


我以这种方式解决了我的问题:

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!");
        }

    }
}

推荐阅读