C# 的空合并运算符 (??) 的作用
C# 中的 "??", 即空合并运算符, 提供了一种简洁的方式来为变量赋值非空值。考虑以下代码示例:
<code class="language-csharp">FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();</code>
这里,空合并运算符用于根据以下条件为 FormsAuth
变量赋值:
<code class="language-csharp">FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();</code>
换句话说,如果 formsAuth
不为空,则将其赋值给 FormsAuth
;否则,创建一个 FormsAuthenticationWrapper
的新实例并将其赋值给 FormsAuth
。这等同于以下条件语句:
<code class="language-csharp">if(formsAuth != null) FormsAuth = formsAuth; else FormsAuth = new FormsAuthenticationWrapper();</code>
这种结构在需要确保变量在使用前已赋值非空值时特别有用。它提供了一种比使用条件语句更简洁高效的替代方案。
需要注意的是,可以连续使用多个空合并运算符。例如:
<code class="language-csharp">string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;</code>
在这个例子中,Answer
变量将被赋值为第一个非空的 Answer
值。如果所有 Answer
值都为空,则 Answer
将保持为空。
此外,值得强调的是,虽然空合并运算符的展开形式在概念上是等价的,但每个表达式只会被评估一次。当表达式涉及具有副作用的方法调用时,这一点至关重要。
以上是``?的详细内容。更多信息请关注PHP中文网其他相关文章!