【发布时间】:2014-08-14 21:57:13
【问题描述】:
我有一个列表,有时它为空或为空。我希望能够检查它是否包含任何列表项,如果没有,则将对象添加到列表中。
// I have a list, sometimes it doesn't have any data added to it
var myList = new List<object>();
// Expression is always false
if (myList == null)
Console.WriteLine("List is never null");
if (myList[0] == null)
myList.Add("new item");
//Errors encountered: Index was out of range. Must be non-negative and less than the size of the collection.
// Inner Exception says "null"
【问题讨论】:
-
请将您接受的答案更改为 L-Four 的答案,因为它比我的要好得多,而且这个问题似乎对许多人有用,因此请选择更好的答案。