为什么Null Coalesce运算符仍然返回null?

Kha*_*laf -5 c# null-coalescing-operator nullreferenceexception

我有这个例程:

    try
    {
        CurrentSessionName = SelectedSession?.Name ?? "No Session Selected";
        CurrentSessionTolerance = SelectedSession?.Tolerance.ToString() ?? "N/A";
        CurrentSessionVerification = SelectedSession?.Verification.Description ?? "N/A";
    }
    catch (Exception ex)
    {
        var whatever = ex.GetType(); // hits here with no provided information
        Console.WriteLine("Null Reference Exception"); // ignores this
        string name = SelectedSession?.Name; // and this
    }
Run Code Online (Sandbox Code Playgroud)

那么为什么NullReferenceException即使SelectedSession不是Null ,它仍会抛出错误?

Jam*_*iec 5

空传播算子很棒 - 但它并没有神奇地消除空值.

这个片段

SelectedSession?.Tolerance
Run Code Online (Sandbox Code Playgroud)

如果SelectedSession为null,则不会出现错误,但它会传播,以便上面的结果为null.这同样适用,如果SelectedSession为空,但Tolerence空.

问题是你然后尝试调用ToString()null

SelectedSession?.Tolerance.ToString()
Run Code Online (Sandbox Code Playgroud)