在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
当前回答
这没什么危险。事实上,它很美。如果需要,可以添加默认值,例如:
CODE
int x = x1 ?? x2 ?? x3 ?? x4 ?? 0;
其他回答
正如在众多答案中正确指出的那样,“空合并运算符”(??),说到它,您可能还想看看它的表亲“空条件运算符”(.或?[),它是一个多次与??一起使用的运算符??
空条件运算符
用于在执行成员访问(?.)或索引(?[)操作之前测试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;
这更加冗长和麻烦。
这没什么危险。事实上,它很美。如果需要,可以添加默认值,例如:
CODE
int x = x1 ?? x2 ?? x3 ?? x4 ?? 0;
它是空合并运算符。
http://msdn.microsoft.com/en-us/library/ms173224.aspx
是的,几乎不可能搜索,除非你知道它叫什么!:-)
编辑:这是另一个问题的一个很酷的特点。你可以把它们拴起来。
C#的隐藏功能?
它是一个空合并运算符,其工作方式与三元运算符类似。
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
这里的一些使用合并获取值的示例效率很低。
你真正想要的是:
return _formsAuthWrapper = _formsAuthWrapper ?? new FormsAuthenticationWrapper();
or
return _formsAuthWrapper ?? (_formsAuthWrapper = new FormsAuthenticationWrapper());
这将防止每次重新创建对象。这将确保在创建新对象时分配私有变量,而不是保持私有变量为空并在每次请求时创建新对象。