可能是重复问题:
C#中两个问号一起是什么意思?
我正在尝试理解这个语句的作用:"??"是什么意思? 这是一种if语句吗?
string cookieKey = "SearchDisplayType" + key ?? "";
可能是重复问题:
C#中两个问号一起是什么意思?
我正在尝试理解这个语句的作用:"??"是什么意思? 这是一种if语句吗?
string cookieKey = "SearchDisplayType" + key ?? "";
这是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();
}
与使用空值合并运算符在单行中完成相比,这需要大量的代码。var foo = null;
- nothrowvar foo = (object)null;
或者 var foo = (SomeClass)null;
来保持变量名称对齐,使代码易于阅读。 - Enigmativity这是这个。但实际上不是。
实际上,它是指这个,以及这个、这个、这个和这个等等。我使用万能的谷歌搜索它们,因为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;
这是空值合并运算符。在这种情况下,它大致相当于:
string cookieKey;
string temp = "SearchDisplayType" + key;
if (temp == null)
cookieKey = "";
else
cookieKey = temp;
而且,既然"SearchDisplayType" + key
永远不会是null
,这与以下代码完全等价:
string cookieKey = "SearchDisplayType" + key;
??
与 +
优先级并且在 OP 的示例中是多余的答案。 - Ani这是空值合并运算符。
这意味着如果key
不为null,它将使用key的值,如果key为null,则使用值""
。
?? 是 null-coalescing 运算符。
来自 MSDN:
?? 运算符被称为 null-coalescing 运算符,用于为可空值类型和引用类型定义默认值。如果左操作数不为 null,则返回左操作数;否则返回右操作数。
但请注意,在您的情况下,表达式的左部分不能为 null,因为它是字符串常量与变量的连接。如果 key 为 null,则 "SearchDisplayType" + key 将计算为 "SearchDisplayType"。
我猜您的语句的意图可以这样实现:
string cookieKey = key==null ? "" : "SearchDisplayType"+key;
??
(这个词或短语需要更多的上下文才能进行准确翻译)