Tim*_*Tim -1 c# null-coalescing-operator .net-3.5
这是一个错误还是我解释'??' - 运算符错了?查看下面的获取属性和评论.
我正在使用C#.NET 3.5
private List<MyType> _myTypeList;
private List<MyType> MyTypeList
{
get
{
//The two code lines below should each behave as the three under, but they don't?
//The ones uncommented are working, the commented result in my list always returning empty (newly created I suppose).
//return _myTypeList ?? new List<MyType>();
//return _myTypeList == null ? new List<MyType>() : _myTypeList;
if (_myTypeList == null)
_myTypeList = new List<MyType>();
return _myTypeList;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:对于那些在新问题时看过这个问题的人,很抱歉,那里的一些错误让每个人都感到困惑.
感谢所有伟大而快速的反馈!我现在明白了我犯的错误.谢谢!
这一行:
return _myTypeList == null ? new List<MyType>() : _myTypeList;
Run Code Online (Sandbox Code Playgroud)
相当于:
if (_myTypeList == null)
return new List<MyType>();
return _myTypeList;
Run Code Online (Sandbox Code Playgroud)
不是:
if (_myTypeList == null)
_myTypeList = new List<MyType>();
return _myTypeList;
Run Code Online (Sandbox Code Playgroud)
与版本??
,你后来添加的,是如此不可读,我不会分析它.让我们?
先行.
如果你必须??
使用它就像
_myTypeList = _myTypeList ?? new List<MyType>();
return _myTypeList;
Run Code Online (Sandbox Code Playgroud)
但是一个简单的if也是好的