在这行代码中运行:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。


当前回答

正如在众多答案中正确指出的那样,“空合并运算符”(??),说到它,您可能还想看看它的表亲“空条件运算符”(.或?[),它是一个多次与??一起使用的运算符??

空条件运算符

用于在执行成员访问(?.)或索引(?[)操作之前测试null。这些运算符可以帮助您编写更少的代码来处理null检查,尤其是在数据结构下降时。

例如:

// if 'customers' or 'Order' property or 'Price' property  is null,
// dollarAmount will be 0 
// otherwise dollarAmount will be equal to 'customers.Order.Price'

int dollarAmount = customers?.Order?.Price ?? 0; 

没有?。和这样做是

int dollarAmount = customers != null 
                   && customers.Order!=null
                   && customers.Order.Price!=null 
                    ? customers.Order.Price : 0; 

这更加冗长和麻烦。

其他回答

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

相当于

FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

但它很酷的一点是,你可以像其他人说的那样,把它们拴起来。没有提到的一点是,您实际上可以使用它来抛出异常。

A = A ?? B ?? throw new Exception("A and B are both NULL");

仅供消遣(知道你们都是C#家伙;-)。

我认为它起源于Smalltalk,在那里它已经存在了很多年。其定义如下:

在对象中:

? anArgument
    ^ self

在UndefinedObject(也称为nil的类)中:

? anArgument
    ^ anArgument

这既有评估版(?),也有非评估版本(??)。它经常出现在惰性初始化的私有(实例)变量的getter方法中,在真正需要之前,这些变量保持为零。

这是三元运算符的短手。

FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();

或者对于那些不做三元的人:

if (formsAuth != null)
{
  FormsAuth = formsAuth;
}
else
{
  FormsAuth = new FormsAuthenticationWrapper();
}

?? 当值为null时,为可为null的类型提供值。因此,如果formsAuth为空,它将返回新的FormsAuthenticationWrapper()。

它是一个空合并运算符,其工作方式与三元运算符类似。

    a ?? b  => a !=null ? a : b 

另一个有趣的点是,“可为null的类型可以包含值,也可以是未定义的”。因此,如果尝试将可为null的值类型分配给不可为null值类型您将得到一个编译时错误。

int? x = null; // x is nullable value type
int z = 0; // z is non-nullable value type
z = x; // compile error will be there.

所以要使用??操作员:

z = x ?? 1; // with ?? operator there are no issues