加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 检查空或空列表

发布时间:2020-12-15 04:00:48 所属栏目:百科 来源:网络整理
导读:我有一个列表,有时它是空的或是空的.我想要检查它是否包含任何字符串,如果没有,然后添加一个字符串到列表. var myList = new Liststring(); // I have a list,sometimes it doesn't have any data added to itif (myList == null) Console.WriteLine("List i
我有一个列表,有时它是空的或是空的.我想要检查它是否包含任何字符串,如果没有,然后添加一个字符串到列表.
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>不会为空,但不会有元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读