Background: C# : The New and Improved C# 6.0Perché la propagazione nulla non funziona per gli eventi?
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) => { };
}
}
Dal momento che l'operatore +=
è lo zucchero sintattico per chiamare il metodo Add della manifestazione, mi sarei aspettato che l'ultima riga compila proprio come la chiamata a DoSomething()
(e che doesn' fare qualsiasi cosa in fase di esecuzione).
Cosa ti aspetteresti che accada se questo fosse permesso e 'outer' fosse nullo? – DavidG
@DavidG Vedere l'annotazione tra parentesi, non dovrebbe fare nulla, proprio come la chiamata a DoSomething() –
Ma si noterà anche che non si può fare 'outer? .Inner.Value = 42;' – DavidG