String.IsNullOrEmpty 与 String.IsNullOrWhiteSpace

String.IsNullOrEmpty

指示指定的字符串是否为 null 或者 空字符串;

返回值:如果参数为 null 或者 空字符串("" 、String.Empty),结果为true,否则为false。

等效于以下代码:

result = s == null || s == String.Empty;

 

String.IsNullOrWhiteSpace

指示指定的字符串是否为 null、空字符串 或者 仅由空字符组成。

返回值:如果参数为 null 、 空字符串("" 、String.Empty) 或者 仅由空字符组成,结果为true,否则为false。

等效于以下代码:

result = String.IsNullOrEmpty(s) || s.Trim().Length == 0;

 

测试代码:

 1             string s1 = null;
 2             string s2 = string.Empty;
 3             string s3 = "";
 4             string s4 = "    ";
 5             string s5 = "\t";
 6 
 7             try
 8             {
 9                 Console.WriteLine("The length of '{0}' is {1}.", s1, s1.Length);
10             }
11             catch (NullReferenceException ex)
12             {
13                 Console.WriteLine(ex.Message);
14             }
15             Console.WriteLine("The length of '{0}' is {1}.", s2, s2.Length);
16             Console.WriteLine("The length of '{0}' is {1}.", s3, s3.Length);
17             Console.WriteLine("The length of '{0}' is {1}.", s4, s4.Length);
18             Console.WriteLine("The length of '{0}' is {1}.", s5, s5.Length);
19 
20             Console.WriteLine("-------------------------------------------------------");
21 
22             Console.WriteLine(string.IsNullOrEmpty(s1));
23             Console.WriteLine(string.IsNullOrEmpty(s2));
24             Console.WriteLine(string.IsNullOrEmpty(s3));
25             Console.WriteLine(string.IsNullOrEmpty(s4));
26             Console.WriteLine(string.IsNullOrEmpty(s5));
27 
28             Console.WriteLine("-------------------------------------------------------");
29 
30             Console.WriteLine(string.IsNullOrWhiteSpace(s1));
31             Console.WriteLine(string.IsNullOrWhiteSpace(s2));
32             Console.WriteLine(string.IsNullOrWhiteSpace(s3));
33             Console.WriteLine(string.IsNullOrWhiteSpace(s4));
34             Console.WriteLine(string.IsNullOrWhiteSpace(s5));

结果:

未将对象引用设置到对象的实例。
The length of '' is 0.
The length of '' is 0.
The length of '    ' is 4.
The length of ' ' is 1.
-------------------------------------------------------
True
True
True
False
False
-------------------------------------------------------
True
True
True
True
True

 

 

相关资料:

https://msdn.microsoft.com/zh-cn/library/system.string.isnullorempty(v=vs.110).aspx

https://msdn.microsoft.com/zh-cn/library/system.string.isnullorwhitespace(v=vs.110).aspx

 

转载于:https://www.cnblogs.com/fanful/p/8324437.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值