在这行代码中运行:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

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


当前回答

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

其他回答

只是因为还没有人说过这个神奇的词:它是空合并运算符。它在C#3.0语言规范的第7.12节中定义。

它非常方便,特别是因为它在表达式中多次使用时的工作方式。形式的表达式:

a ?? b ?? c ?? d

将给出表达式a的结果,如果它是非空的,否则尝试b,否则尝试c,否则尝试d。它在每个点都短路。

此外,如果d的类型不可为null,则整个表达式的类型也不可为空。

接合运算符

相当于

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

相当于

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

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

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

这是三元运算符的短手。

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

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

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

其他人已经很好地描述了空合并运算符。在需要对null进行一次测试的情况下,缩短的语法??=可以增加可读性。

传统空测试:

if (myvariable == null)
{
    myvariable = new MyConstructor();
}

使用空合并运算符,这可以写成:

myvariable = myvariable ?? new MyConstructor();

其也可以用缩短的语法编写:

myvariable ??= new MyConstructor();

有些人觉得它更易读、简洁。