C#中的双问号有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1608174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:20:06  来源:igfitidea点击:

What does a double question mark do in C#?

c#null-coalescing-operatornull-coalescing

提问by tom d

Possible Duplicates:
?? Null Coalescing Operator --> What does coalescing mean?
What do two question marks together mean in C#?

可能的重复:
?? 空合并运算符 --> 合并是什么意思?
C#中两个问号放在一起是什么意思?

I couldn't find this question being asked here so I figured I would ask it. What does a double question mark do in C#?

我在这里找不到这个问题,所以我想我会问这个问题。C#中的双问号有什么作用?

Example:

例子:

x = y ?? z;

采纳答案by Alexis Abril

This is a null coalescing operator. The method above states x is assigned y's value, unless y is null, in which case it is assigned z's value.

这是一个空合并运算符。上面的方法指出 x 被分配了 y 的值,除非 y 为空,在这种情况下,它被分配了 z 的值。

回答by Spencer Ruport

If y is null x will be set to z.

如果 y 为空,则 x 将设置为 z。

回答by CodeSpeaker

Use yif not null, otherwise use z.

使用y如果没有null,否则使用z

回答by Michael Edwards

If a the value y is null then the value z is assigned.

如果 a 值 y 为空,则分配值 z。

For example:

例如:

x = Person.Name ?? "No Name";

If name is null x will have the value "No Name"

如果名称为空 x 将具有值“无名称”

回答by Austin Salonen

From Wikipedia:

来自维基百科

It's the null-coalesce operator and shorthand for this:

这是空合并运算符和它的简写:

x = (y != null ? y : z);

回答by itsmatt

As others have stated, it is the null coalescing operator.

正如其他人所说,它是空合并运算符。

MSDN information on this:

关于这个的 MSDN 信息:

https://docs.microsoft.com/dotnet/csharp/language-reference/operators/null-coalescing-operator

https://docs.microsoft.com/dotnet/csharp/language-reference/operators/null-coalescing-operator

回答by 123Developer

.Net framework 2.0 onwards allow null values to Nullable value types.

.Net 框架 2.0 以后允许空值到 Nullable 值类型。

here in this case, it says x equals y if it has some value (ie not null) or else equals z

在这种情况下,它说 x 等于 y 如果它有某个值(即不为空),否则等于 z