C#中IsNullOrEmpty和IsNullOrWhiteSpace的区别

194

这些C#命令有什么区别?

string text= "  ";
1-string.IsNullOrEmpty(text.Trim())

2-string.IsNullOrWhiteSpace(text)

1
请参考以下链接:http://msdn.microsoft.com/zh-cn/library/system.string.isnullorempty.aspx 和 http://msdn.microsoft.com/zh-cn/library/system.string.isnullorwhitespace.aspx。 - ojlovecd
7
"IsNullOrWhiteSpace" 包含了 "IsNullOrEmpty" (请参见 TGH 的答案)。 - samus
8个回答

256

IsNullOrWhiteSpace 是一个方便的方法,类似于以下代码,但它具有更高的性能:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

空白字符由Unicode标准定义。IsNullOrWhiteSpace方法将任何传递给Char.IsWhiteSpace方法并返回true值的字符解释为空白字符。


2
实际上,截取空格后的字符串长度测试也会捕捉到空字符串。 - galaxis

113

简短回答:

常用的空格" "、制表符"\t"和换行符"\n"有所区别:

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

https://dotnetfiddle.net/4hkpKM

还可以查看关于:空格字符的答案。


长答案:

还有一些其他的空格字符,你可能以前从未使用过

  • 属于UnicodeCategory.SpaceSeparator类别的字符包括:SPACE(U + 0020),NO-BREAK SPACE(U + 00A0),OGHAM SPACE MARK(U + 1680),EN QUAD(U + 2000),EM QUAD(U + 2001),EN SPACE(U + 2002),EM SPACE(U + 2003),THREE-PER-EM SPACE(U + 2004),FOUR-PER-EM SPACE(U + 2005),SIX-PER-EM SPACE(U + 2006),FIGURE SPACE(U + 2007),PUNCTUATION SPACE(U + 2008),THIN SPACE(U + 2009),HAIR SPACE(U + 200A),NARROW NO-BREAK SPACE(U + 202F),MEDIUM MATHEMATICAL SPACE(U + 205F)和 IDEOGRAPHIC SPACE(U + 3000)。
  • 属于UnicodeCategory.LineSeparator类别的字符仅包括LINE SEPARATOR字符(U + 2028)。
  • 属于UnicodeCategory.ParagraphSeparator类别的字符仅包括PARAGRAPH SEPARATOR字符(U + 2029)。
  • 字符包括CHARACTER TABULATION(U + 0009),LINE FEED(U + 000A),LINE TABULATION(U + 000B),FORM FEED(U + 000C),CARRIAGE RETURN(U + 000D)和NEXT LINE(U + 0085)。

https://learn.microsoft.com/en-us/dotnet/api/system.char.iswhitespace


2
string.IsNullOrWhiteSpace("") 是什么意思? - samus
1
@samusarin 没有区别 https://dotnetfiddle.net/9uWpvh - fubo

62

第一种方法检查字符串是否为 null 或空字符串。在您的示例中,如果在剪裁之前未检查 null,则可能存在 null 引用的风险。

1- string.IsNullOrEmpty(text.Trim())

第二种方法检查字符串是否为 null 或包含任意数量的空格(包括空字符串)

2- string .IsNullOrWhiteSpace(text)

IsNullOrWhiteSpace方法包含了IsNullOrEmpty方法的功能,但如果字符串只包含空格字符,它也会返回true

在您的具体示例中,您应该使用2)作为1)方法中调用可能为空的字符串的Trim可能引发空引用异常。


6
使用C#6,你可以安全地使用string.IsNullOrEmpty(text?.Trim())来判断字符串是否为空。 - goldenratio
所以使用 IsNullOrWhiteSpace 比使用 IsNullOrEmpty 好? - Shaiju T

13

这是反编译后的方法实现。

    public static bool IsNullOrEmpty(String value) 
    {
        return (value == null || value.Length == 0); 
    }

    public static bool IsNullOrWhiteSpace(String value) 
    {
        if (value == null) return true; 

        for(int i = 0; i < value.Length; i++) { 
            if(!Char.IsWhiteSpace(value[i])) return false; 
        }

        return true;
    }

显然,IsNullOrWhiteSpace 方法还会检查传递的值中是否包含空格。

所谓空格是指:https://msdn.microsoft.com/zh-cn/library/system.char.iswhitespace(v=vs.110).aspx


很好,:) 你是如何反编译并查看实现的呢? - Shaiju T
1
使用像dotpeek这样的反编译器。 - Ľuboš Pilka

12

String.IsNullOrEmpty(string value) 方法在字符串为 null 或空时返回true。需要注意的是,空字符串用两个双引号 "" 表示。

String.IsNullOrWhitespace(string value) 方法在字符串为 null、空或仅包含空格或制表符等空白字符时返回true

要查看哪些字符被视为空白字符,请参考此链接: http://msdn.microsoft.com/en-us/library/t809ektx.aspx


4
如果您的字符串(在这种情况下是变量text)可能为空,这将产生很大的影响:
1-string.IsNullOrEmpty(text.Trim()) --> 异常,因为您调用了空对象的方法
2-string.IsNullOrWhiteSpace(text) 这将正常工作,因为内部检查了空问题
要使用第一种选项提供相同的行为,您需要先检查它是否不为空,然后再使用trim()方法。
if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }

3

String.IsNullOrWhiteSpace(text) 应该在大多数情况下使用,因为它还包括只有空格但没有其他文本的空字符串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var str = "";
            
            Console.WriteLine(string.IsNullOrWhiteSpace(str));              
            
        }
    }
}

它返回


你的例子不正确,因为 string.IsNullOrEmpty 会对变量 str 返回 true。 - Azimuth
@Azimuth,我无法完全理解。您能否在https://rextester.com/或您喜欢的任何其他C#在线Fiddle工具上创建一个fiddle? - vibs2006
为什么我要提供一些小例子呢?只需在您的代码中将 IsNullOrWhiteSpace 替换为 IsNullOrEmpty 并运行它即可。它将返回 true。因此,您的示例并未展示 IsNullOrWhiteSpaceIsNullOrEmpty 之间的区别。 - Azimuth
好的,我会做到。感谢@Azimuth的解释。 - vibs2006
string.IsNullOrWhiteSpace 返回此表达式 String.IsNullOrEmpty(value) || value.Trim().Length == 0; 因此,请在入口(Xamarin)验证处理程序的文本框中使用它。 - Sachintha Udara

1
[性能测试] 以防有人想知道,在一个秒表测试中比较:
如果(nopass.Trim().Length > 0)
如果(!string.IsNullOrWhiteSpace(nopass))

以下是结果:

空值的 Trim-Length = 15

非空值的 Trim-Length = 52


当值为空时,IsNullOrWhiteSpace的返回值为11

当值不为空时,IsNullOrWhiteSpace的返回值为12


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接