如何在C#中调度事件

如何在C#中调度事件,第1张

如何在C#中调度事件

在所有库类中都有一种模式。建议您也为自己的类使用,特别是对于框架/库代码。但是当您偏离或跳过一些步骤时,没有人会阻止您。

这是基于最简单的事件委托的示意图

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 patternpublic delegate void Eventhandler(object sender, Eventargs args);// your publishing classclass 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    }}

以及如何使用它:

// your subscribing classclass 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    }}

当您有信息要传递时:

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 varyhandler(this, args);          }    }}class Bar{          void Foo_Changed(object sender, MyEventArgs args)  // the Handler   {       string s = args.Info;       ...   }}

更新资料

从C#6开始,“触发器”方法中的调用代码变得更加容易,可以使用空条件运算符来缩短空测试,

?.
而无需在保持线程安全的情况下进行复制:

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5150648.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存