如何设置eventhandler

时间:2017-01-25 16:25:27

标签: c# visual-studio-2008

下面发布的代码我想从foo1更新进度条。 但是我无法在Foo中实现eventhandler

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 {}

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

1 个答案:

答案 0 :(得分:0)

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

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).aspxhttps://codeblog.jonskeet.uk/2015/01/30/clean-event-handlers-invocation-with-c-6/

相关问题