null-coalescing运算符评估?

时间:2014-07-09 11:12:37

标签: c# .net operators

object bread(food foo)
{
    return foo.ingredient ?? "cheese";
}

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

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

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

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

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

3 个答案:

答案 0 :(得分:5)

如果foo为空,您将获得NullReferenceException

因此,您必须使用三元(如果是其他)而不是合并来处理此案例。

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

答案 1 :(得分:2)

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

foo.ingredient ?? "cheese";

等于:

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

您可能会喜欢,在VS2014 CTP中,他们已经拥有了新的运算符?.,它可以满足您的需求:

foo?.ingredient ?? "cheese";

答案 2 :(得分:1)

当然它会抛出异常。您无法访问该对象的属性,但该属性不存在。如果您希望自己避免错误,可以写下:

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