如何在C#中调度事件

Jan*_*son 19 c# events event-dispatching

我希望创建自己的事件并发送它们.我之前从未在C#中做过这件事,仅在Flex中.我想必须有很多不同之处.

有人能为我提供一个很好的例子吗?

Hen*_*man 46

在所有库类中都使用了一种模式.它也适用于您自己的类,特别是对于框架/库代码.但是当你偏离或跳过几步时,没有人会阻止你.

这是一个基于最简单的事件委托的示意图System.Eventhandler.

// The delegate type. This one is already defined in the library, in the System namespace
// the `void (object, EventArgs)` signature is also the recommended pattern
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
    }
}
Run Code Online (Sandbox Code Playgroud)

以及如何使用它:

// your subscribing class
class Bar
{       
    public Bar()
    {
        Foo f = new Foo();
        f.Changed += Foo_Changed;    // Subscribe, using the short notation
    }

    // the handler must conform to the signature
    void Foo_Changed(object sender, EventArgs args)  // the Handler (reacts)
    {
        // the things Bar has to do when Foo changes
    }
}
Run Code Online (Sandbox Code Playgroud)

当您有信息传递时:

class MyEventArgs : EventArgs    // guideline: derive from EventArgs
{
    public string Info { get; set; }
}

class Foo  
{
    public event EventHandler<MyEventArgs> Changed;    // the Event
    ...
    protected virtual void OnChanged(string info)      // the Trigger
    {
        EventHandler handler = Changed;   // make a copy to be more thread-safe
        if (handler != null)
        {
           var args = new MyEventArgs(){Info = info};  // this part will vary
           handler(this, args);  
        }
    }
}

class Bar
{       
   void Foo_Changed(object sender, MyEventArgs args)  // the Handler
   {
       string s = args.Info;
       ...
   }
}
Run Code Online (Sandbox Code Playgroud)

更新

从C#6开始,'Trigger'方法中的调用代码变得更加容易,使用null-conditional运算符可以缩短null测试,?.而无需复制,同时保持线程安全:

protected virtual void OnChanged(string info)   // the Trigger
{
    var args = new MyEventArgs{Info = info};    // this part will vary
    Changed?.Invoke(this, args);
}
Run Code Online (Sandbox Code Playgroud)