以下是......
SomeType _someProperty;
public SomeType SomeProperty
{
get
{
if (_someProperty == null)
_someProperty = new SomeType();
return _someProperty;
}
}
Run Code Online (Sandbox Code Playgroud)
...具有与以下相同的功能?
SomeType _someProperty;
public SomeType SomeProperty
{
get { return _someProperty ?? (_someProperty = new SomeType()); }
}
Run Code Online (Sandbox Code Playgroud)
根据ReSharper他们的确如此.如果是这样,有人可以解释第二个块的语法吗?
是的,它们是相同的功能.
??是空合并运算符.如果不为null,则运算符返回运算符之前的值,如果前面的值为null,则返回运算符之后的值.
在这种情况下,通过将表达式的第二部分包装在params中,_requiredFieldValidator如果__requiredFieldValidator为null ,则在返回之前将新对象分配给后备字段.
如果没有括号,则在返回之前不会分配,这会导致以下编译错误:
赋值的左侧必须是变量,属性或索引器
括号保证正确计算赋值表达式.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |