如何设置事件处理程序



使用下面发布的代码,我想从foo1更新进度条。但我无法在 Foo 中实现事件处理程序

class Foo : Form        // implements progressbar
{
     IFoo foo = new Foo1()
     // this will not do:
     ProgressBarEventHandler = new EventUpdateProgressBar(this.UpdateProgressBar);
     UpdateProgressBar() { }
}
public delegate void EventUpdateProgressBar();
class FooBase
{
     public EventUpdateProgressBar ProgressBarEventHandler;
     protected virtual void UpdateProgressBar()
     {
        if (ProgressBarEventHandler != null)
           ProgressBarEventHandler();
     }
}
class  Foo1 : IFoo,FooBase { base.UpdateProgressBar() }
class  Foo2 : IFoo,FooBase {}
interface IFoo {}

有没有办法让它工作或有更好的方法?

我不完全确定您的意图是什么,但是如果您尝试实现两个类,其中一个引发事件而另一个处理它们,那么最小示例将如下所示。

delegate void MyEvent();
class MyEventSource
{
    public event MyEvent Event;
    public void RaiseEvent()
    {
        MyEvent evt = Event;
        if (evt != null)
            evt();
    }
}
class MyEventListener
{
    public void SubscribeForEventFromMyEventSource(MyEventSource eventSource)
    {
        eventSource.Event += this.EventHandler;
    }
    public void EventHandler()
    {
        //  Event handling logic here
    }
}

有关事件的更多阅读材料可在此处获得:https://msdn.microsoft.com/en-us/library/9aackb16(v=vs.110).aspx此处 https://codeblog.jonskeet.uk/2015/01/30/clean-event-handlers-invocation-with-c-6/

最新更新