这些C#命令有什么区别?
string text= " ";
1-string.IsNullOrEmpty(text.Trim())
2-string.IsNullOrWhiteSpace(text)
这些C#命令有什么区别?
string text= " ";
1-string.IsNullOrEmpty(text.Trim())
2-string.IsNullOrWhiteSpace(text)
IsNullOrWhiteSpace
是一个方便的方法,类似于以下代码,但它具有更高的性能:
return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
空白字符由Unicode标准定义。
IsNullOrWhiteSpace
方法将任何传递给Char.IsWhiteSpace
方法并返回true值的字符解释为空白字符。
简短回答:
常用的空格" "
、制表符"\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
还可以查看关于:空格字符的答案。
长答案:
还有一些其他的空格字符,你可能以前从未使用过
https://learn.microsoft.com/en-us/dotnet/api/system.char.iswhitespace
string.IsNullOrWhiteSpace("")
是什么意思? - samus第一种方法检查字符串是否为 null 或空字符串。在您的示例中,如果在剪裁之前未检查 null,则可能存在 null 引用的风险。
1- string.IsNullOrEmpty(text.Trim())
第二种方法检查字符串是否为 null 或包含任意数量的空格(包括空字符串)
2- string .IsNullOrWhiteSpace(text)
IsNullOrWhiteSpace
方法包含了IsNullOrEmpty
方法的功能,但如果字符串只包含空格字符,它也会返回true
。
在您的具体示例中,您应该使用2)作为1)方法中调用可能为空的字符串的Trim
可能引发空引用异常。
string.IsNullOrEmpty(text?.Trim())
来判断字符串是否为空。 - goldenratioIsNullOrWhiteSpace
比使用 IsNullOrEmpty
好? - Shaiju T这是反编译后的方法实现。
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
String.IsNullOrEmpty(string value)
方法在字符串为 null 或空时返回true
。需要注意的是,空字符串用两个双引号 "" 表示。
String.IsNullOrWhitespace(string value)
方法在字符串为 null、空或仅包含空格或制表符等空白字符时返回true
。
要查看哪些字符被视为空白字符,请参考此链接: http://msdn.microsoft.com/en-us/library/t809ektx.aspx
text
)可能为空,这将产生很大的影响:string.IsNullOrEmpty(text.Trim())
--> 异常,因为您调用了空对象的方法string.IsNullOrWhiteSpace(text)
这将正常工作,因为内部检查了空问题if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }
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。 - AzimuthIsNullOrWhiteSpace
替换为 IsNullOrEmpty
并运行它即可。它将返回 true
。因此,您的示例并未展示 IsNullOrWhiteSpace
和 IsNullOrEmpty
之间的区别。 - Azimuth以下是结果:
空值的 Trim-Length = 15
非空值的 Trim-Length = 52
当值为空时,IsNullOrWhiteSpace的返回值为11
当值不为空时,IsNullOrWhiteSpace的返回值为12