[英]What does "??" mean?
我正在查看 ASP.NET MVC 1.0 生成的代码,并且想知道; 双问号是什么意思?
// This constructor is not used by the MVC framework but is instead provided for ease
// of unit testing this type. See the comments at the end of this file for more
// information.
public AccountController(IFormsAuthentication formsAuth, IMembershipService service)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = service ?? new AccountMembershipService();
}
这是空合并运算符。 如果该值不为空,它将返回左侧的值,否则返回右侧的值(即使它为空)。 它们通常链接在一起,以默认值结尾。
意思是一样的
If (formsAuth != null)
FormsAuth = formsAuth;
else
FormsAuth = FormsAuthenticationService();
它是空合并运算符
来自 MSDN
这 ?? 运算符称为空值合并运算符,用于为可空值类型和引用类型定义默认值。 如果它不为空,则返回左操作数; 否则返回正确的操作数。
可空类型可以包含一个值,也可以是未定义的。 这 ?? 运算符定义将可空类型分配给不可空类型时要返回的默认值。 如果您尝试将可空值类型分配给不可空值类型而不使用 ?? 运算符,您将生成编译时错误。 如果您使用强制转换,并且当前未定义可空值类型,则会引发 InvalidOperationException 异常。
有关详细信息,请参阅Nullable 类型(C# 编程指南)。
的结果?? 即使它的两个参数都是常量,运算符也不被视为常量。
它是空合并运算符。 如果左边的值为空,它将返回右边的值。
如果 formsAuth 为 null,则返回右侧的值( new FormsAuthenticationService() )。
这意味着:如果它不是 NULL,则返回第一个值(例如“formsAuth”),否则返回第二个值(新 FormsAuthenticationService()):
马克
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.