在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
当前回答
如果您熟悉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";
其他回答
谢谢大家,这里是我在MSDN网站上找到的最简洁的解释:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
两个问号(??)表示它是一个联合运算符。
合并运算符返回链中的第一个非空值。你可以看到这段youtube视频,它实际演示了整个事情。
但让我补充一下视频中的内容。
如果你看到联合的英文意思,它会说“巩固在一起”。例如,下面是一个链接四个字符串的简单合并代码。
因此,如果str1为空,它将尝试str2,如果str2为空,则将尝试str3,依此类推,直到找到具有非空值的字符串。
string final = str1 ?? str2 ?? str3 ?? str4;
简单来说,合并运算符返回链中的第一个非NULL值。
正如在众多答案中正确指出的那样,“空合并运算符”(??),说到它,您可能还想看看它的表亲“空条件运算符”(.或?[),它是一个多次与??一起使用的运算符??
空条件运算符
用于在执行成员访问(?.)或索引(?[)操作之前测试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;
这更加冗长和麻烦。
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
相当于
FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
但它很酷的一点是,你可以像其他人说的那样,把它们拴起来。没有提到的一点是,您实际上可以使用它来抛出异常。
A = A ?? B ?? throw new Exception("A and B are both NULL");
这里的一些使用合并获取值的示例效率很低。
你真正想要的是:
return _formsAuthWrapper = _formsAuthWrapper ?? new FormsAuthenticationWrapper();
or
return _formsAuthWrapper ?? (_formsAuthWrapper = new FormsAuthenticationWrapper());
这将防止每次重新创建对象。这将确保在创建新对象时分配私有变量,而不是保持私有变量为空并在每次请求时创建新对象。