加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 委托,我不明白的事件约定

发布时间:2020-12-16 00:18:44 所属栏目:百科 来源:网络整理
导读:我在C#中简要介绍了这个例子 ( http://www.albahari.com/nutshell/ch04.aspx) using System;public class PriceChangedEventArgs : EventArgs{ public readonly decimal LastPrice; public readonly decimal NewPrice; public PriceChangedEventArgs (decima
我在C#中简要介绍了这个例子
( http://www.albahari.com/nutshell/ch04.aspx)

using System;

public class PriceChangedEventArgs : EventArgs
{
  public readonly decimal LastPrice;
  public readonly decimal NewPrice;

  public PriceChangedEventArgs (decimal lastPrice,decimal newPrice)
  {
    LastPrice = lastPrice; NewPrice = newPrice;
  }
}

public class Stock
{
  string symbol;
  decimal price;

  public Stock (string symbol) {this.symbol = symbol;}

  public event EventHandler<PriceChangedEventArgs> PriceChanged;

  ****protected virtual void OnPriceChanged (PriceChangedEventArgs e)
  {
    if (PriceChanged != null) PriceChanged (this,e);
  }****

  public decimal Price
  {
    get { return price; }
    set
    {
      if (price == value) return;
      OnPriceChanged (new PriceChangedEventArgs (price,value));
      price = value;
    }  
  }
}

class Test
{
  static void Main()
  {
    Stock stock = new Stock ("THPW");
    stock.Price = 27.10M;
    // register with the PriceChanged event    
    stock.PriceChanged += stock_PriceChanged;
    stock.Price = 31.59M;
  }

  static void stock_PriceChanged (object sender,PriceChangedEventArgs e)
  {
    if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
      Console.WriteLine ("Alert,10% stock price increase!");
  }
}

我不明白,为什么使用这个惯例…

****protected virtual void OnPriceChanged (PriceChangedEventArgs e)
  {
    if (PriceChanged != null) PriceChanged (this,e);
  }****

为什么我需要这种方法,为什么我要给它“this”参数?!?我不能直接用测试类中的方法PriceChanged附加该类中的事件并跳过该方法吗?

解决方法

由于(事件)委托列表不为空,因此使用空检查,但如果没有订户,则为空.

但是,它不是线程安全的.因此,如果您开始使用BackgroundWorker或任何其他多线程技术,它可能会爆炸.

我建议您使用空委托:

public event EventHandler<PriceChangedEventArgs> PriceChanged = delegate {};

因为它允许你只写:

protected virtual void OnPriceChanged (PriceChangedEventArgs e)
{
   PriceChanged (this,e);
}

它是线程安全的,代码更容易阅读.

why do I care to give it the “this” parameter?!?

多个事件生成器可能使用相同的事件处理程序.发件人告诉调用的生成者.您应该始终按预期发送正确的事件生成器,如果不这样做,您将打破打开/关闭原则

Why Do I need that method?

你没有,除非你会重复代码(例如生成EventArgs类)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读