gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:40:49 27 4
gpt4 key购买 nike

背景: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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com