我有一个列表,有时它是空的或是空的.我想要检查它是否包含任何字符串,如果没有,然后添加一个字符串到列表.
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>不会为空,但不会有元素.