如果空合并操作中的所有参数都为空,结果是什么?

发布于 2024-09-28 01:00:59 字数 160 浏览 1 评论 0原文

当这段代码完成时,myObject 的结果是什么?

object myObject = "something";
object yourObject = null;

myObject = null ?? yourObject;

When this code finishes, what is the result of myObject?

object myObject = "something";
object yourObject = null;

myObject = null ?? yourObject;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雪若未夕 2024-10-05 01:00:59

myObject 将为 null

这被翻译为 -

if (null == null)
    myObject = yourObject;
else
    myObject = null;

myObject will be null

This gets translated to -

if (null == null)
    myObject = yourObject;
else
    myObject = null;
星光不落少年眉 2024-10-05 01:00:59

合并运算符可以翻译为:

x ?? y
x != null ? x : y

因此你所拥有的:

myObject = null != null ? null : yourObject;

这实际上是毫无意义的,因为 null 永远是 null。

The coalesce operator translates to this:

x ?? y
x != null ? x : y

Therefore what you have:

myObject = null != null ? null : yourObject;

Which is actually pretty pointless since null will always be null.

弥枳 2024-10-05 01:00:59

只是为了好玩,这里有一个小表:

A    ?? B    -> R
---------------------
a    ?? any  -> a; where a is not-null
null ?? b    -> b; for any b
null ?? null -> null; implied from previous

由于 ?? 只是一个(惊讶!)右关联中缀运算符,因此 x ??是吗? z --> <代码>x ?? (y ?? z) 。与&&||一样,??也是一种短路操作。

...来自 ?运算符(C# 参考)

<块引用>

如果左侧操作数不为 null,则 It (??) 返回左侧操作数;否则返回正确的操作数。

...来自 C# 3.0 语言参考:

<块引用>

形式为 ?? 的空合并表达式b 要求 a 为可为空类型或引用类型。如果 a 非空,则 a ?? 的结果b 是 a;否则,结果为b。仅当 a 为 null 时,该操作才会计算 b。

Just for kicks, here is a small table:

A    ?? B    -> R
---------------------
a    ?? any  -> a; where a is not-null
null ?? b    -> b; for any b
null ?? null -> null; implied from previous

And since ?? is just a (surprise!) right-associated infix operator, x ?? y ?? z --> x ?? (y ?? z). Like && and ||, ?? is also a short-circuiting operation.

...from ?? Operator (C# Reference):

It (??) returns the left-hand operand if it is not null; otherwise it returns the right operand.

...from the C# 3.0 Language reference:

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文