object bread(food foo)
{
return foo.ingredient ?? "cheese";
}
Run Code Online (Sandbox Code Playgroud)
如果foo退出,但成分是null,我得到"cheese".我的问题,包括一个假设:
如果foo本身null将"chesse"被退回或将抛出ArgutmentNullException?
我的GUESS是NullCoalescingOperator的实现或多或少是这样的:
object nco(object lhs, object rhs)
{
if(lhs != null)
return lhs;
else
return rhs;
}
Run Code Online (Sandbox Code Playgroud)
因此,传递 foo.ingredient已经导致异常(因为您无法检查您没有的对象中的字段),因此它被抛出.
会有意义的.
这个想法是否正确/如何实施nco以及为什么?
你会得到一个NullReferenceExceptionif foo为null.
所以你必须用三元(如果不是)而不是合并来处理这种情况.
return (foo == null || foo.ingredient == null)
? "cheese"
: foo.ingredient;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |