背景: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()
一样(并且它没有&#39 ; t在运行时做任何事情)。
答案 0 :(得分:5)
out.ti.final
运算符确实是方法调用的语法糖,但它是一个运算符,而不是方法调用。
+=
运算符左侧的代码为:
+=
该运算符左侧的代码需要评估可以分配给它的内容,并在其上定义outer?.Inner.Event
运算符(例如,委托类型的变量)或事件。
此代码无法评估为+
的事件,这就是为什么它是非法的。