在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
当前回答
这是三元运算符的短手。
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
或者对于那些不做三元的人:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}
其他回答
它是空合并运算符,非常像三元(立即if)运算符。另见??操作员-MSDN。
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
扩展到:
FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
其进一步扩展到:
if(formsAuth != null)
FormsAuth = formsAuth;
else
FormsAuth = new FormsAuthenticationWrapper();
在英语中,它的意思是“如果左边的东西不是空的,就用那个,否则就用右边的东西。”
请注意,您可以按顺序使用任意数量的这些。以下语句将为Answer分配第一个非空的Answer#(如果所有Answer均为空,则Answer为空):
string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;
另外值得一提的是,虽然上面的展开在概念上是等价的,但每个表达式的结果只计算一次。例如,如果表达式是具有副作用的方法调用,这一点很重要。(感谢@Joey指出了这一点。)
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
相当于
FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
但它很酷的一点是,你可以像其他人说的那样,把它们拴起来。没有提到的一点是,您实际上可以使用它来抛出异常。
A = A ?? B ?? throw new Exception("A and B are both NULL");
?? 当值为null时,为可为null的类型提供值。因此,如果formsAuth为空,它将返回新的FormsAuthenticationWrapper()。
只是因为还没有人说过这个神奇的词:它是空合并运算符。它在C#3.0语言规范的第7.12节中定义。
它非常方便,特别是因为它在表达式中多次使用时的工作方式。形式的表达式:
a ?? b ?? c ?? d
将给出表达式a的结果,如果它是非空的,否则尝试b,否则尝试c,否则尝试d。它在每个点都短路。
此外,如果d的类型不可为null,则整个表达式的类型也不可为空。
这是三元运算符的短手。
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
或者对于那些不做三元的人:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}