QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 1359|回复: 0

[C#] 检查集合是否为空

[复制链接]

等级头衔

积分成就    金币 : 2806
   泡泡 : 1516
   精华 : 6
   在线时间 : 1244 小时
   最后登录 : 2024-5-5

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2022-10-15 11:49:57 | 显示全部楼层 |阅读模式
一、概述
4 w9 {' y' \8 O. @' V       当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举.
) r: v; w( M3 o- Y* [% E5 H9 a0 ]9 h二、是否为 null7 X% i: o" @; G+ c" g9 B  Z
       如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式:+ Z3 Q& ^3 E* h' l. f, W
方式一:== null; i& d% M$ b. W" K% ?& B) D
  1. class Program
  2.     {
  3.         static List<Student> stuList;
  4.         static void Main(string[] args)
  5.         {
  6.             if (stuList == null)
  7.             {
  8.                 Console.WriteLine("stuList is null");
  9.             }
  10.             Console.ReadKey();
  11.         }
  12.     }
  13.     public class Student
  14.     {
  15.         public string Name { get; set; }
  16.         public int Age { get; set; }
  17.     }
1.jpg

3 q1 J7 N4 r- J; \+ h+ w. `! o方式二:is null
# R7 h; h; N# \  i9 E$ ^
  1. if (stuList is null)
三、是否为空2 U3 i5 C! h* I5 B
       在上面我们先判断了集合不为null以后,如果还需要检查集合是否有元素,也是有多种方式可以实现:1 }. F. @; {. k6 m
方式一:stuList.Count == 0& G/ w! n/ X: i
  1. if (stuList.Count == 0)
  2.             {
  3.                 Console.WriteLine("stuList is empty");
  4.             }
2.jpg

/ @# [; j1 V6 X; [5 S: ~' V- H; y/ R  S方式二:!stuList.Any()   //     确定序列是否包含任何元素。/ ^/ \" a) H- j# {2 K
// 返回结果:
6 N0 I- Z# j/ K) D* j// true 如果源序列中不包含任何元素,则否则为 false。0 q; T% M2 Y8 o$ u
  1. if (!stuList.Any())
  2.             {
  3.                 Console.WriteLine("stuList is empty");
  4.             }
      那如果我既想检查他是否为null又想检查是否为null,有没有简洁点的语法呢?这时候我们就可以用 ?. 来操作了。
. H. ^3 p% j7 V+ C实例如下:
  1. class Program
  2.     {
  3.         static List<Student> stuList = new List<Student>();
  4.         static void Main(string[] args)
  5.         {
  6.             //if (stuList is null)
  7.             //{
  8.             //    Console.WriteLine("stuList is null");
  9.             //    throw new Exception("stuList is null");
  10.             //}
  11.             //if (!stuList.Any())
  12.             //{
  13.             //    Console.WriteLine("stuList is empty");
  14.             //}
  15.             stuList.Add(new Student() { Name = "zls",Age = 25});
  16.             if (stuList?.Count != 0)
  17.             {
  18.                 Console.WriteLine("StuList is neither null nor empty");
  19.             }
  20.             Console.ReadKey();
  21.         }
  22.     }
  23.     public class Student
  24.     {
  25.         public string Name { get; set; }
  26.         public int Age { get; set; }
  27.     }
3.jpg

/ B1 K5 |4 o1 h  ^       这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。
, C* q; D' V  l( G
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-5-7 17:50

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表