Null条件运算符为事件抛出空引用

本文关键字:引用 事件 条件运算符 Null | 更新日期: 2023-09-27 18:13:01

据我所知,空条件运算符(?.)在运行下一位代码之前检查是否为空,但在此代码中:

public delegate void EventArgs(object Sender, PlayerPage Page);
public event EventArgs PageChanged;
private PlayerPage _CurrentPage = PlayerPage.NoPage;
public PlayerPage CurrentPage
{
    get { return _CurrentPage; }
    set { _CurrentPage = value; PropertyChangedFire(); this?.PageChanged(this,value); }
}

但这个? .PageChanged(这个值);抛出空引用异常

编辑:

哦…我真笨!.Invoke();感谢您的快速回复

Null条件运算符为事件抛出空引用

需要检查PageChanged是否为空。然后你可以在它上面调用Invoke来引发事件。

PageChanged?.Invoke(this,value);
边注:这正是Resharper推荐的c# 6

也许不是你想的那样?

?.检查this是否为空*)。实际上,this很难为空。

public event EventArgs PageChanged;事件。当没有附加处理程序时,事件的"值"为空。此时,调用this?.PageChanged(this,value);会抛出。我很确定就是这种情况,并且它与?.运算符没有任何关系,该运算符应用于this

*)我的意思是,你当前的代码相当于:

set
{
    _CurrentPage = value;
    PropertyChangedFire();
    if(this!=null)
        this.PageChanged(this,value);
}

而要正确调用事件,需要:

set
{
    _CurrentPage = value;
    PropertyChangedFire();
    if(this.PageChanged!=null)
        this.PageChanged(this,value);
}

或者更确切地说,是线程安全的:

set
{
    _CurrentPage = value;
    PropertyChangedFire();
    var localref = this.PageChanged;
    if(localref!=null)
        localref(this,value);
}