应使用 String.IsNullOrEmpty() 判断字符串是否为 null 或空字符串,因其内部已处理 null 安全;而 == "" 或 .Length == 0 在 null 时会抛 NullReferenceException;注意它不识别纯空白字符串,需用 IsNullOrWhiteSpace()。

直接用 String.IsNullOrEmpty() 就行,它专门用来判断字符串是否为 null 或空字符串("")。 这是最常用、最安全的方式,不用自己写一堆条件判断。
== "" 或 .Length == 0?因为如果字符串是 null,调用 .Length 或 .Equals("") 会直接抛出 NullReferenceException。而 IsNullOrEmpty 内部已做 null 检查,不会崩。
语法很简单:
string 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
比如给空值设默认值:
string displayName = userName ?? "游客";基本上就这些。用对方法,代码更稳也更干净。
以上就是C#怎么判断字符串是否为空 C# String.IsNullOrEmpty使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号