微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/csharp/93032.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐