Err*_*ain 61 c# null-coalescing-operator null-coalescing
如何编写以下方案的简写?
get
{
if (_rows == null)
{
_rows = new List<Row>();
}
return _rows;
}
Run Code Online (Sandbox Code Playgroud)
Zei*_*kki 81
使用null-coalescing运算符(??):
get
{
_rows = _rows ?? new List<Row>();
return _rows;
}
Run Code Online (Sandbox Code Playgroud)
或(不太可读):
get { return _rows ?? (_rows = new List<Row>()); }
Run Code Online (Sandbox Code Playgroud)
?? ?? operator被称为null-coalescing运算符.如果操作数不为null,则返回左侧操作数; 否则它返回右手操作数.
Rom*_*ner 41
这是懒惰的初始化模式,因此直接的方法是使用Lazy <T>类.
class Foo
{
Lazy<List<Row>> _rows;
public Foo()
{
_rows = new Lazy(() => new List<Row>());
}
public List<Row> Rows
{
get { return _rows.Value; }
}
}
Run Code Online (Sandbox Code Playgroud)
这具有额外的优点,即它不会用初始化逻辑"污染"吸气剂.
Dmi*_*nko 20
我建议三元运算符
get {
return _rows == null ? _rows = new List<Row>() : _rows;
}
Run Code Online (Sandbox Code Playgroud)
或者因为空List<Row>没有带来太大的开销,为什么不摆脱显式_row字段并实现只读属性(C#6.0语法):
public IList<Row> Rows {get;} = new List<Row>();
Run Code Online (Sandbox Code Playgroud)
jpm*_*c26 18
这是一个更好的主意:防止_rows永远存在null.
使您的构造函数初始化变量:
public MyClass()
{
this._rows = new List<Row>();
}
Run Code Online (Sandbox Code Playgroud)
然后你的财产就是
get
{
return this._rows;
}
Run Code Online (Sandbox Code Playgroud)
确保如果需要"清除"变量,则始终调用其Clear方法或分配新的空列表而不是分配null.如果您真的需要在整个班级中使其清晰且一致,则可能在方法中对该操作进行编码.
这是很多更符合逻辑.如果你的变量永远不应该null,那就永远不应该null.它还巧妙地避免了条件和具有getter修改状态的问题.
Sin*_*atr 12
List<Row> _rows;
public List<Row> Rows => _rows ?? (_rows = new List<Row>());
Run Code Online (Sandbox Code Playgroud)
Ric*_*ett 10
正如其他人所说,您可以在此方案中使用null-coalescing运算符.
get
{
return _rows ?? (_rows = new List<Row>());
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,这是ReSharper建议的那种变化(他们称之为快速修复).
在你的例子中,它将在if声明下放置一个小的波形.将鼠标悬停在它上面会显示出如何更改/简化代码的建议.
稍后点击几下,即可实施更改.
return _rows ?? (_rows = new List<Row>());
Run Code Online (Sandbox Code Playgroud)