栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在C#中调度事件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442736.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号