【问题标题】:null-coalescing operator evaluation?空合并运算符评估?
【发布时间】:2014-07-09 11:12:36
【问题描述】:
object bread(food foo)
{
    return foo.ingredient ?? "cheese";
}

如果 foo 退出,但成分是 null,我得到 "cheese"。 我的问题,包括一个假设:
如果 foo 本身是 null 将返回 "chesse" 还是会抛出 ArgutmentNullException

我的猜测是 NullCoalescingOperator 或多或少是这样实现的:

object nco(object lhs, object rhs)
{
    if(lhs != null)
        return lhs;
    else
        return rhs;
}

因此通过 foo.ingredient 已经导致异常(因为您无法检查您没有的对象中的字段),因此它被抛出。
会有意义。

这个想法是否正确/nco 是如何实施的?为什么?

【问题讨论】:

  • 您是指?? 还是??什么 C# 版本?我已经阅读过类似 foo?.ingredient 的语法,但我不确定它是否已进入 C#。
  • 如果foo为空,你会得到NullReferenceException
  • @CodeCaster ?? 当然。谢谢。
  • 您可以通过在一个简单的测试项目中尝试您的面包示例来断言您自己的假设。你不这样做的原因是什么?
  • 请注意,在some versions of C# 中将允许使用return foo?.ingredient ?? "cheese";,其中运算符?. 是C# 中的新运算符。查看我的链接。

标签: c# .net operators


【解决方案1】:

如果 foo 为 null,您将获得 NullReferenceException

所以你必须用三元(if else)而不是合并来处理这种情况。

return (foo == null || foo.ingredient == null) 
           ? "cheese" 
           : foo.ingredient;

【讨论】:

  • 答案加上实现预期的方法,我什至没有要求,亲爱的。
【解决方案2】:

是的,你的想法是绝对正确的,因为:

foo.ingredient ?? "cheese";

等于:

foo.ingredient != null ? foo.ingredient : "cheese";

你可能喜欢什么,在 VS2014 CTP 中他们已经有了新的运算符?.,它将满足你的需要:

foo?.ingredient ?? "cheese";

【讨论】:

    【解决方案3】:

    当然会抛出异常。您无法访问该对象的属性,该属性不存在。如果你想保护自己免受错误,你可以写:

    return (foo == null) ? "cheese" : (foo.ingredient ?? "cheese");
    

    【讨论】:

    • 我可以看到 Raphaël Althaus 的回答更加简洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2014-11-29
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多