c# – 检查空或空列表

前端之家收集整理的这篇文章主要介绍了c# – 检查空或空列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个列表,有时它是空的或是空的.我想要检查它是否包含任何字符串,如果没有,然后添加一个字符串到列表.
var myList = new List<string>(); // I have a list,sometimes it doesn't have any data added to it
if (myList == null) Console.WriteLine("List is never null"); // Expression is always false
if (myList[0] == null) myList.Add("new item"); 
// Index was out of range. Must be non-negative and less than the size of the collection.
// Inner Exception says "null"

解决方法

你需要这个:
if(myList.Count == 0){
    // nothing is there. Add here
}

基本上新的List< T>不会为空,但不会有元素.

原文链接:https://www.f2er.com/csharp/93032.html

猜你在找的C#相关文章