你如何在C#中举办活动?

Beh*_*joo 2 c# events event-handling

股票数据下载类有一个BarList,它可以添加新的条形或更新,并在最后一个条形实时更改时替换最后一个条形.每当此下载类向BarList类添加新栏或更改其最后一个栏时,它也会调用其NotifyOnBarsAdded或NotifyOnBarChanges.我正在尝试使用notify方法来引发事件,以便处理这些事件的Canvas类可以根据调用的notify方法重绘最后一个条形图或整个图形.问题是当调用NotifyOnBarsAdded类时,我得到一个NullReferenceException,试图引发事件.我正在举办这样的活动:NotifyBarAdded(this, EventArgs.Empty).这是不正确的?这是代码:

public class BarList : List< Bar >
{
    private int historyHandle;
    public event EventHandler NotifyBarChanged;
    public event EventHandler NotifyBarAdded;

    public BarList(int historyHandle)
    {
        this.historyHandle = historyHandle;
    }

    public BarList()
    {
        // TODO: Complete member initialization
    }

    public void NotifyOnBarChange()
    {
        NotifyBarChanged(this,EventArgs.Empty);
    }

    public void NotifyOnBarsAdded()
    {
         NotifyBarAdded(this, EventArgs.Empty);
    }

    public long handle { get; set; }


}
Run Code Online (Sandbox Code Playgroud)

Bri*_*sen 5

你正在做的是正确的,除了你必须考虑到没有附加事件处理程序,这将给你一个NullReferenceException.您必须在调用或使用像这样的空委托初始化事件之前插入空值.

检查null:

var local = NotifyBarAdded;
if(local != null) local(this, EventArgs.Empty);
Run Code Online (Sandbox Code Playgroud)

使用空委托进行初始化将允许您保留已有的调用(即不需要检查null).

public event EventHandler NotifyBarAdded = delegate {};
Run Code Online (Sandbox Code Playgroud)