c# - 为什么空传播对事件不起作用?

标签 c#

背景:C# : The New and Improved C# 6.0

using System;

internal sealed class Program
{
    private sealed class Inner
    {
        internal int Value { get; } = 42;
        internal void DoSomething(int value) { }
        internal event EventHandler Event;
    }

    private sealed class Outer
    {
        internal Inner Inner { get; } = new Inner();
    }

    private static void Main(string[] args)
    {
        Outer outer = null;

        // Works as expected (does not call Inner and Value, val is null)
        int? val = outer?.Inner.Value;

        // Works as expected (does not call Inner and DoSomething)
        outer?.Inner.DoSomething(42);

        // CS0070: The event 'Program.Inner.Event' can only appear on the left hand
        // side of += or -= (except when used from within the type 'Program.Inner')
        outer?.Inner.Event += (s, e) => { };
    }
}

由于 += 运算符只是调用事件的 add 方法的语法糖,我本以为最后一行编译就像调用 DoSomething()(并且它在运行时不执行任何操作)。

最佳答案

+= 运算符确实是方法调用的语法糖,但它是运算符,而不是方法调用。

+= 运算符左侧的代码是:

outer?.Inner.Event

该运算符左侧的代码需要评估可以分配给并定义了 + 运算符的东西(例如委托(delegate)类型的变量)或事件。

如果 outer == null,此代码无法评估为事件,这就是它非法的原因。

关于c# - 为什么空传播对事件不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33304747/

相关文章:

c# - 我能否以类似于此 C++ 示例的方式实例化 C# 类?

c# - WPF 将过滤后的 ObservableCollection ICollectionView 绑定(bind)到 Combobox

c# - 使用 C# 和 gppg,我将如何构建抽象语法树?

c# - MSIL 代码中的变量作用域/重用

c# - ^= 运算符到底是做什么的?

c# - 在 ObservableCollection 内绑定(bind) ObservableCollection

c# - Windows 窗体 WebBrowser 控件 - 支持 Javascript?

C# Linq Char 数组 Except() - 奇怪的行为

c# - 提取与每个字符串开头的模式匹配的字符串列表

c# - 以编程方式打开高级安全设置对话框?