【问题标题】:what is ? operator in NotifyPropertyChanged [duplicate]什么是 ? NotifyPropertyChanged 中的运算符 [重复]
【发布时间】:2025-12-12 19:55:02
【问题描述】:

我遇到过类似的代码

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));

我试图在上面的代码行中找到PropertyChanged? 的含义。

【问题讨论】:

    标签: c# wpf inotifypropertychanged


    【解决方案1】:

    这是 null 传播 的语法,它是 introduced in c# 6.0。这里的? 是空条件运算符。这段代码相当于:

    if(!(PropertyChanged is null))
        PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propName));
    

    【讨论】:

    • 更多的是var handler = PropertyChanged; if (handler != null) { handler.Invoke... }。这是线程安全的,你的代码不是。
    • @SimonMourier 你的代码并不比我的更线程安全。
    • @Soleil 错误,在您的代码中,PropertyChanged 可能在 null 检查和 Invoke 调用之间变为 null。
    • @Soleil 在多线程应用程序中,可以在空检查和调用之间清除事件处理程序,从而触发异常。复制可以防止这种情况发生。