【转载】C#中string.IsNullOrEmpty和string.IsNullOrWhiteSpace区别

在C#中判断字段是否为空或者Null的时候,我们一般会使用到string.IsNullOrEmpty和string.IsNullOrWhiteSpace方法,这两个方法在大部分情况下判断的结果是一致的,但相比于string.IsNullOrEmpty方法,string.IsNullOrWhiteSpace方法还会对空白字符进行判断,例如一个字符串全是空格等空白字符的情况,在string.IsNullOrEmpty的判断下为false,而string.IsNullOrWhiteSpace方法判断则为true。

举例如下:

 string stringD = "   ";//空白字符串

var resultD1 = string.IsNullOrEmpty(stringD);
 var resultD2= string.IsNullOrWhiteSpace(stringD);

上述语句的结果resultD1=false,resultD2=true。string.IsNullOrWhiteSpace方法认定为这种空白字符也是符合规则的,因此返回true。

备注:原文转载自博主个人站IT技术小趣屋,原文链接为C#中string.IsNullOrEmpty和string.IsNullOrWhiteSpace区别_IT技术小趣屋

原文地址:https://www.cnblogs.com/xu-yi/p/10993535.html