在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
在这行代码中运行:
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
这两个问号是什么意思,是某种三元运算符吗?在谷歌里很难查到。
当前回答
谢谢大家,这里是我在MSDN网站上找到的最简洁的解释:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
其他回答
它是空合并运算符。
http://msdn.microsoft.com/en-us/library/ms173224.aspx
是的,几乎不可能搜索,除非你知道它叫什么!:-)
编辑:这是另一个问题的一个很酷的特点。你可以把它们拴起来。
C#的隐藏功能?
这是三元运算符的短手。
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();
有些人觉得它更易读、简洁。
?? 当值为null时,为可为null的类型提供值。因此,如果formsAuth为空,它将返回新的FormsAuthenticationWrapper()。
谢谢大家,这里是我在MSDN网站上找到的最简洁的解释:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;