在C#中,如果一个List()对象不为null,那是否也意味着它Count总是大于0?
例如,如果您有一个intList类型的对象,List<int>以下代码是多余的?
if (intList != null && intList.Count > 0) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
不,有一个空列表是完全有效的:
List<int> intList = new List<int>();
bool isEmpty = intList.Count == 0; // true
Run Code Online (Sandbox Code Playgroud)
如果您想知道列表是否为空且包含至少一个项目,您还可以使用新的C#6 空条件运算符:
List<int> intList = null;
bool isNotEmpty = intList?.Count > 0; // no exception, false
Run Code Online (Sandbox Code Playgroud)