在.NET 开发中,字符串判空是高频基础操作,不同 “空” 场景(纯空值、空字符串、全空白字符)对应不同检测方式,选对方法能避免业务逻辑漏洞。本文从基础概念、核心方法、场景适配三方面,讲解.NET 中字符串判空的核心技巧。
在.NET 中,字符串的 “空” 主要分三类,判空前需先区分场景:
最基础的判空方式,可直接检测null或空字符串"",但无法识别空白字符串。
string str1 = null;
string str2 = "";
string str3 = " ";
// 结果:true(检测null)
bool isNull1 = str1 == null;
// 结果:true(检测空字符串)
bool isEmpty2 = str2 == "";
// 结果:false(无法识别空白字符串)
bool isEmpty3 = str3 == "";
⚠️ 注意:str == "" 等价于 str == string.Empty,string.Empty 是.NET 提供的空字符串常量,语义更清晰,推荐优先使用。
.NET 内置静态方法,专门检测 “null 或 空字符串”,是日常开发中最常用的基础判空方法。
string str1 = null;
string str2 = "";
string str3 = " ";
// 结果:true
bool isNullOrEmpty1 = string.IsNullOrEmpty(str1);
// 结果:true
bool isNullOrEmpty2 = string.IsNullOrEmpty(str2);
// 结果:false(不检测空白字符)
bool isNullOrEmpty3 = string.IsNullOrEmpty(str3);
.NET 4.0 及以上版本新增,覆盖 “null、空字符串、全空白字符” 所有空场景,适合需要过滤 “无有效内容” 字符串的场景(如用户输入校验)。
string str1 = null;
string str2 = "";
string str3 = " \n"; // 包含空格+换行符
// 结果:true
bool isNullOrWhiteSpace1 = string.IsNullOrWhiteSpace(str1);
// 结果:true
bool isNullOrWhiteSpace2 = string.IsNullOrWhiteSpace(str2);
// 结果:true(识别空白字符)
bool isNullOrWhiteSpace3 = string.IsNullOrWhiteSpace(str3);
通过字符串长度判断,需先避免null导致的空引用异常,适合需精准控制长度的场景。
string str = "test";
// 先判null,再判长度(避免NullReferenceException)
bool isEmpty = str != null && str.Length == 0;
- 避免直接调用
str.Trim() == ""判空:若str为null,调用Trim()会抛出NullReferenceException,需先判null;
.NET Core/.NET 5+中,string.IsNullOrWhiteSpace()性能已优化,无需手动实现空白字符判断;
- 数据库 / 配置文件读取的字符串,优先用
string.IsNullOrWhiteSpace(),避免空白字符导致的 “看似有值实则无效” 问题。
.NET 字符串判空的核心是 “匹配业务场景”:基础场景用IsNullOrEmpty,需过滤空白用IsNullOrWhiteSpace,精准控制长度结合Length属性。掌握这三类方法,即可覆盖 99% 的判空需求,避免因 “空” 场景遗漏导致的 bug。