事件不会被事件消耗

问题描述 投票:0回答:1

我试图理解在C#中引发和消费事件。

我无法消耗我提出的事件。

你能看一下我的代码吗?谢谢

class Program
{
    static void Main(string[] args)
    {
        var evtClass = new EventClass();
        evtClass.OnVariableLoaded(new EventClass.CustomEventArgs("test"));ded;
    }

    static void c_VariableLoaded(object sender, EventClass.CustomEventArgs e)
    {
        // The event is not being executed...
    }
}
public class EventClass
{
    public event EventHandler<CustomEventArgs> VariableLoaded;

    protected virtual void OnVariableLoaded(CustomEventArgs eventArgs)
    {
        VariableLoaded?.Invoke(this, eventArgs);
    }

    public class CustomEventArgs : EventArgs
    {
        public CustomEventArgs(string variable1)
        {
            Variable1 = variable1;
        }

        public string Variable1 { get; }
    }
}
c# .net events
1个回答
1
投票

在您的代码中,您只需订阅活动

evtClass.VariableLoaded += c_VariableLoaded;

但没有呼吁这个事件。有些东西必须从evtClass中调用它,因为main中的事件处理程序可以解决。

例如,考虑查看Windows窗体事件。您正在使用某个事件处理程序订阅Button Click事件 - 就像在您的主要事件中一样。但是你必须按下按钮才能运行处理程序的代码。

所以它在您的代码中 - 您订阅了事件,但事件本身从未被提出。要从代码中提高它,你应该用你构造的一些args调用OnVariableLoaded

考虑查找一些事件示例 - 例如,进度条更新或PropertyChanged模式。

© www.soinside.com 2019 - 2024. All rights reserved.