字符串
字符串为空情况有4种,如下:
string str1 = "";
string str2 = " ";
string str3 = String.Empty;
string str4 = null;
判断方法
C#判断字符串的string类的方法有2个,定义如下:
//
// 摘要:
// 指示指定的字符串是 null 还是 System.String.Empty 字符串。
//
// 参数:
// value:
// 要测试的字符串。
//
// 返回结果:
// 如果 true 参数为 value 或空字符串 (""),则为 null;否则为 false。
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(String value);
//
// 摘要:
// 指示指定的字符串是 null、空还是仅由空白字符组成。
//
// 参数:
// value:
// 要测试的字符串。
//
// 返回结果:
// 如果 true 参数为 value 或 null,或者如果 System.String.Empty 仅由空白字符组成,则为 value。
public static bool IsNullOrWhiteSpace(String value);
测试代码
- 使用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();
输出:
2. 使用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();
输出:
结论
由此得出,这两个方法的主要区别就是在判断由空字符组成的字符串,酌情使用。