【问题标题】:Why does the Null Coalesce Operator still return null?为什么 Null Coalesce Operator 仍然返回 null?
【发布时间】:2016-09-30 21:00:35
【问题描述】:

我有这个习惯:

    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
    }

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

【问题讨论】:

  • 您是否尝试在发布模式下进行调试? SelectedSession.ToleranceSelectedSession.Verification 也可以为空。
  • 好吧SelectedSession 不会抛出,因为您使用的是它的空传播。 SelectedSession.ToleranceSelectedSession.Verification 呢?
  • @FirstStep,在 null 上调用 .ToString() 当然会抛出异常。访问空对象的属性也是如此。
  • 总有null在某处。只需要找到它。
  • 您的问题很有趣,但由于它都是关于 NRE 的,它总是会作为关于该主题的规范问题的重复而被关闭。我已经更改了您的问题,以便对我提供的答案有意义 - 我 100% 肯定将来会帮助更多人。

标签: c# nullreferenceexception null-coalescing-operator


【解决方案1】:

Null 传播运算符很棒 - 但它并不能神奇地消除空值。

这个sn-p

SelectedSession?.Tolerance

如果SelectedSession 为空,则不会出错,但它会继续传播,因此上述结果为空。如果SelectedSession not null,但 Tolerence 为 null,则同样适用。

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

SelectedSession?.Tolerance.ToString()

【讨论】:

    【解决方案2】:

    ToleranceVerification 可能为 null,而您正在对空指针调用 ToString() 函数。

    你不能在空指针上调用ToString()

    【讨论】:

    • 那为什么我的编译器没有命中呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-26
    • 1970-01-01
    • 2016-12-28
    相关资源
    最近更新 更多