在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
在这行代码中运行:
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;
这更加冗长和麻烦。
其他回答
?? 当值为null时,为可为null的类型提供值。因此,如果formsAuth为空,它将返回新的FormsAuthenticationWrapper()。
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();
有些人觉得它更易读、简洁。
谢谢大家,这里是我在MSDN网站上找到的最简洁的解释:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;