是否使用string. isnullorempty (string)检查字符串时,认为有string. isnullowhitespace (string)在。net 4.0及以上?


当前回答

它们是不同的函数。你应该根据你的情况决定你需要什么。

我不认为使用它们中的任何一种是不好的做法。大多数情况下,IsNullOrEmpty()就足够了。但你可以选择:)

其他回答

实践中的差异:

string testString = "";
Console.WriteLine(string.Format("IsNullOrEmpty : {0}", string.IsNullOrEmpty(testString)));
Console.WriteLine(string.Format("IsNullOrWhiteSpace : {0}", string.IsNullOrWhiteSpace(testString)));
Console.ReadKey();

Result :
IsNullOrEmpty : True
IsNullOrWhiteSpace : True

**************************************************************
string testString = " MDS   ";

IsNullOrEmpty : False
IsNullOrWhiteSpace : False

**************************************************************
string testString = "   ";

IsNullOrEmpty : False
IsNullOrWhiteSpace : True

**************************************************************
string testString = string.Empty;

IsNullOrEmpty : True
IsNullOrWhiteSpace : True

**************************************************************
string testString = null;

IsNullOrEmpty : True
IsNullOrWhiteSpace : True

string. isnullorempty (str) -如果你想检查字符串值是否已提供

string.IsNullOrWhiteSpace(str)——基本上这已经是一种业务逻辑实现(例如,为什么“”是坏的,但像“~~”这样的东西是好的)。

我的建议是——不要将业务逻辑与技术检查混为一谈。 例如,字符串。IsNullOrEmpty最适合在方法的开头使用,以检查其输入参数。

这个怎么样?

if (string.IsNullOrEmpty(x.Trim())
{
}

这将修剪所有的空格,如果它们在那里,避免IsWhiteSpace的性能损失,这将使字符串满足“空”条件,如果它不是空的。

我也认为这是更清楚的,它通常是一个很好的实践,修剪字符串,特别是如果你把它们放入数据库或其他东西。

注意转义字符:

String.IsNullOrEmpty(""); //True
String.IsNullOrEmpty(null); //True
String.IsNullOrEmpty("   "); //False
String.IsNullOrEmpty("\n"); //False
String.IsNullOrEmpty("\t"); //False
String.IsNullOrEmpty("hello"); //False

在这里:

String.IsNullOrWhiteSpace("");//True
String.IsNullOrWhiteSpace(null);//True
String.IsNullOrWhiteSpace("   ");//True
String.IsNullOrWhiteSpace("\n");//True
String.IsNullOrWhiteSpace("\t");//True
String.IsNullOrWhiteSpace("hello");//False

如果对传递给IsNullOrEmpty()的值应用Trim,两个方法的结果将是相同的。

就性能而言,IsNullOrWhiteSpace()会更快。

它说它所有的IsNullOrEmpty()不包括白间距,而IsNullOrWhiteSpace()做!

IsNullOrEmpty() 零 空

IsNullOrWhiteSpace()如果字符串是: 零 空 -只包含空白