直接用 String.IsNullOrEmpty()
就行,它专门用来判断字符串是否为 null
或空字符串(""
)。 这是最常用、最安全的方式,不用自己写一堆条件判断。
为什么不能只用 == ""
或 .Length == 0
?
因为如果字符串是
null,调用
.Length或
.Equals("") 会直接抛出 NullReferenceException。而
IsNullOrEmpty内部已做
null检查,不会崩。
基本用法:一行搞定
语法很简单:
string str = null;if (string.IsNullOrEmpty(str)) { /* 是空或null */ }
常见写法包括:
if (string.IsNullOrEmpty(input)) throw new ArgumentException("输入不能为空");
var result = string.IsNullOrEmpty(name) ? "未知" : name;
if (!string.IsNullOrEmpty(text)) Process(text);(先取反,处理非空情况)
注意:它不判断“空白字符串”(比如只有空格)
IsNullOrEmpty(" ") 返回 true吗?不,返回
false。因为
" "是非空字符串(长度 > 0),只是内容全是空白。
如果想连空白也过滤掉,用
string.IsNullOrWhiteSpace():
string.IsNullOrWhiteSpace(null)→
true
string.IsNullOrWhiteSpace("") → true
string.IsNullOrWhiteSpace(" \t\n ") → true
扩展小提示:C# 6.0+ 可用空合并运算符简化赋值
比如给空值设默认值:
string displayName = userName ?? "游客";// 等价于:string displayName = string.IsNullOrEmpty(userName) ? "游客" : userName;
基本上就这些。用对方法,代码更稳也更干净。
