什么'??' 在C#中意味着什么?

Tro*_*roj 8 .net c# asp.net

可能重复:
C#中两个问号共同意味着什么?

我试图理解这个判断的作用:"??" 意思?如果if-statment,这是som类型吗?

string cookieKey = "SearchDisplayType" + key ?? "";
Run Code Online (Sandbox Code Playgroud)

djd*_*d87 14

它是Null Coalescing运算符.这意味着如果第一部分具有值,则返回该值,否则返回第二部分.

例如:

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

object something = foo ?? rar;
something == "Hello"; // true
Run Code Online (Sandbox Code Playgroud)

或者一些实际的代码:

IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customerList = customers as IList<Customer> ?? 
    customers.ToList();
Run Code Online (Sandbox Code Playgroud)

这个例子正在做的是将客户作为一个客户IList<Customer>.如果此强制转换结果为null,则它将ToList在客户IEnumerable上调用LINQ 方法.

可比较的if语句是这样的:

IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customersList = customers as IList<Customer>;
if (customersList == null)
{
     customersList = customers.ToList();
}
Run Code Online (Sandbox Code Playgroud)

与使用null-coalescing运算符在单行内执行相比,这是很多代码.

  • 只有一点 - >你不能做`var foo = null;` (2认同)

Mar*_*ngs 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;
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

754 次

最近记录:

15 年,4 月 前