C#中的'??'是什么意思?

8

可能是重复问题:
C#中两个问号一起是什么意思?

我正在尝试理解这个语句的作用:"??"是什么意思? 这是一种if语句吗?

string cookieKey = "SearchDisplayType" + key ?? "";

4
如果有人在SO上搜索"??",这将被视为重复,例如此处。 :-( - Martin Hennings
5
  1. 开始使用C#。
  2. ?? (这个词或短语需要更多的上下文才能进行准确翻译)
  3. 获利!
- leppie
注意运算符优先级,参考链接:http://msdn.microsoft.com/zh-cn/library/6a71f45d.aspx - tom3k
我指的是运算符 ?? 应用于整个语句:"SearchDisplayType" + key,key 始终不为空。 - tom3k
是的,你说得对,这个问题在这里(供参考)已经讨论过了。自己要注意:使用空值合并运算符时,总是要加上括号... - Martin Hennings
7个回答

14

这是Null Coalescing运算符的作用。如果第一个部分有值,则返回该值,否则返回第二个部分。

例如:

object foo = null;
object rar = "Hello";

object something = foo ?? rar;
something == "Hello"; // true

或者是一些实际的代码:

IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customerList = customers as IList<Customer> ?? 
    customers.ToList();

这个例子的作用是将顾客转换为一个 IList<Customer>。如果此转换结果为空,则会在顾客 IEnumerable 上调用 LINQ 的 ToList 方法。

相应的 if 语句如下:

IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customersList = customers as IList<Customer>;
if (customersList == null)
{
     customersList = customers.ToList();
}
与使用空值合并运算符在单行中完成相比,这需要大量的代码。

2
只有一个要点 -> 你不能做 var foo = null; - nothrow
@Yossarian - 是的,说得好,但那只是伪代码。我已经修改了以避免混淆。 - djdd87
@Yossarian - 你可以使用 var foo = (object)null; 或者 var foo = (SomeClass)null; 来保持变量名称对齐,使代码易于阅读。 - Enigmativity

5

这是这个。但实际上不是。

实际上,它是指这个,以及这个这个这个这个等等。我使用万能的谷歌搜索它们,因为SO没有在答案中搜索的功能(正确吗?),因此很难找到这种问题的重复项。对于未来,请将其用作参考。;-)

它被称为null-coalescing运算符。它基本上与

int? nullableDemoInteger;
// ...
int someValue = nullableDemoInteger ?? -1;
// basically same as
int someValue = nullableDemoInteger.HasValue ? nullableDemoInteger.Value : -1;
// basically same as
int someValue;
if(nullableDemoInteger.HasValue)
    someValue = nullableDemoInteger.Value;
else
    someValue = -1;

在我看来,“??” 最好的用法是可空类型。 - abatishchev

4

这是空值合并运算符。在这种情况下,它大致相当于:

string cookieKey;
string temp = "SearchDisplayType" + key;
if (temp == null)
    cookieKey = "";
else
    cookieKey = temp;

而且,既然"SearchDisplayType" + key永远不会是null,这与以下代码完全等价:

string cookieKey = "SearchDisplayType" + key;

+1。比我先回答了。目前为止唯一提到 ??+ 优先级并且在 OP 的示例中是多余的答案。 - Ani
错误的。如果(key == null),而不是如果(“SearchDisplayType”+ key)== null)。 - Goran
@Goran:不,LukeH是正确的。也许这不是很直观,但试一下就知道了。 - Ani
1
@Goran:为什么你不在下投票之前实际尝试一下呢? - LukeH
我写了:int? y = null; string x = "test" + y ?? ""; 输出的是"test"而不是""。 - Goran
我明白为什么-你能稍微编辑一下答案吗(我的投票已被锁定)? - Goran

2

1

1

这是空值合并运算符。

这意味着如果key不为null,它将使用key的值,如果key为null,则使用值""


1

?? 是 null-coalescing 运算符。

来自 MSDN:

?? 运算符被称为 null-coalescing 运算符,用于为可空值类型和引用类型定义默认值。如果左操作数不为 null,则返回左操作数;否则返回右操作数。

但请注意,在您的情况下,表达式的左部分不能为 null,因为它是字符串常量与变量的连接。如果 key 为 null,则 "SearchDisplayType" + key 将计算为 "SearchDisplayType"。

我猜您的语句的意图可以这样实现:

string cookieKey = key==null ? "" : "SearchDisplayType"+key;

使用此代码,如果键为空,则cookieKey设置为空字符串,否则设置为"SearchDisplayType"+key的连接。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接