一、C#判断字符串对象是否为空的几种方式,如下:
string == "";
string == null;
string == String.Empty;
string.length == 0
string.IsNullOrEmpty( str )
string. IsNullOrWhiteSpace(object)
二、测试代码
IsNullOrEmpty函数
string str1 = "";
string str2 = " ";
string str3 = String.Empty;
string str4 = null;
if (string.IsNullOrEmpty(str1))
{
Console.WriteLine("str1");
}
if (string.IsNullOrEmpty(str2))
{
Console.WriteLine("str2");
}
if (string.IsNullOrEmpty(str3))
{
Console.WriteLine("str3");
}
if (string.IsNullOrEmpty(str4))
{
Console.WriteLine("str4");
}
Console.ReadKey();
输出结果:

IsNullOrWhiteSpace函数
string str1 = "";
string str2 = " ";
string str3 = String.Empty;
string str4 = null;
if (string.IsNullOrWhiteSpace(str1))
{
Console.WriteLine("str1");
}
if (string.IsNullOrWhiteSpace(str2))
{
Console.WriteLine("str2");
}
if (string.IsNullOrWhiteSpace(str3))
{
Console.WriteLine("str3");
}
if (string.IsNullOrWhiteSpace(str4))
{
Console.WriteLine("str4");
}
Console.ReadKey();
输出结果:

执行效率:string. IsNullOrWhiteSpace(object) > string.IsNullOrEmpty(object) > object.Length() == 0 > object == string.Empty > object == “”
本文详细介绍了在C#中检查字符串是否为空的五种方法,包括string == string == null, string == String.Empty, string.Length == 0以及string.IsNullOrEmpty和string.IsNullOrWhiteSpace。通过测试代码展示了它们在不同情况下的应用,并讨论了执行效率,指出string.IsNullOrWhiteSpace(object)的效率高于string.IsNullOrEmpty(object),而直接比较长度和空字符串最慢。
709

被折叠的 条评论
为什么被折叠?



