在这行代码中运行:
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;
这更加冗长和麻烦。
其他回答
它是空合并运算符。
http://msdn.microsoft.com/en-us/library/ms173224.aspx
是的,几乎不可能搜索,除非你知道它叫什么!:-)
编辑:这是另一个问题的一个很酷的特点。你可以把它们拴起来。
C#的隐藏功能?
这个运算符称为空合并运算符。如果操作数不为空,则返回左侧操作数;否则返回右手操作数。
int? variable1 = null;
int variable2 = variable1 ?? 100;
如果variable1不为空,则将variable2设置为variable1的值;否则,如果variable1==null,则将variable2设置为100。
谢谢大家,这里是我在MSDN网站上找到的最简洁的解释:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
如果您熟悉Ruby,那么它的||=似乎类似于C#的??给我。这是一些红宝石:
irb(main):001:0> str1 = nil
=> nil
irb(main):002:0> str1 ||= "new value"
=> "new value"
irb(main):003:0> str2 = "old value"
=> "old value"
irb(main):004:0> str2 ||= "another new value"
=> "old value"
irb(main):005:0> str1
=> "new value"
irb(main):006:0> str2
=> "old value"
在C#中:
string str1 = null;
str1 = str1 ?? "new value";
string str2 = "old value";
str2 = str2 ?? "another new value";
只是因为还没有人说过这个神奇的词:它是空合并运算符。它在C#3.0语言规范的第7.12节中定义。
它非常方便,特别是因为它在表达式中多次使用时的工作方式。形式的表达式:
a ?? b ?? c ?? d
将给出表达式a的结果,如果它是非空的,否则尝试b,否则尝试c,否则尝试d。它在每个点都短路。
此外,如果d的类型不可为null,则整个表达式的类型也不可为空。