在 C# 中,“非空”(Not Null / Not Empty)的概念

在 C# 中,“非空”(Not Null / Not Empty)的概念非常清晰,并且随着 C# 版本的迭代,语法也变得越来越优雅。

C# 中的“空”主要分为两种:引用为空(null)字符串内容为空(Empty)。以下是 C# 中处理非空校验的几种常见场景和最佳实践:

1. 判断对象/变量非空(Not Null)

这是最基础的判断,确保对象存在,防止抛出 NullReferenceException

  • 传统写法
    if (obj != null) 
    {
        // 安全使用 obj
    }
    
  • C# 7.0+ 模式匹配(推荐)
    if (obj is not null) // 比 != null 更简洁,且在泛型中更安全
    {
        // 安全使用 obj
    }
    

2. 判断字符串非空(Not Empty / Not NullOrEmpty)

字符串是 C# 中最特殊的类型,它既可能是 null,也可能是 ""

  • 仅判断不为空字符串(前提是确定它不是 null):
    if (str != "") // 或者 str.Length > 0
    
  • 判断既不是 null,也不是空字符串(最常用)
    if (!string.IsNullOrEmpty(str)) // 等价于 str != null && str != ""
    
  • 判断既不是 null,也不是空字符串,也不是纯空格
    if (!string.IsNullOrWhiteSpace(str)) // 强烈推荐用于处理用户输入
    

3. 可空值类型(Nullable Value Types)

对于 int?, DateTime? 等结构体,它们可以为 null

int? age = null;

if (age.HasValue) // 判断非空
{
    int realAge = age.Value; // 安全获取值
}

// 或者使用 C# 7.0+ 的模式匹配
if (age is int realAge) 
{
    // realAge 已经是一个安全的 int 值
}

4. 空条件运算符(Null-conditional Operator)

当你只需要在“非空”时调用方法或获取属性时,可以使用 ?.,这能极大简化代码:

// 如果 person 非空,且 Address 非空,才获取 City;否则返回 null
string city = person?.Address?.City; 

// 如果 list 非空,才获取 Count,否则返回 0
int count = list?.Count ?? 0; 

5. 参数级别的非空校验(C# 11+ 新特性)

如果你在方法开头需要校验参数是否为空,C# 11 引入了 ArgumentNullException.ThrowIfNull,一行代码搞定:

public void ProcessData(string data)
{
    ArgumentNullException.ThrowIfNull(data); // 如果 data 为 null,直接抛出异常
    
    // 下面的代码可以放心使用 data,无需再判空
}

总结建议:
在 C# 中,尽量避免手写 if (str != null && str != "") 这种冗长的代码。对于字符串,无脑使用 !string.IsNullOrWhiteSpace();对于普通对象,使用 is not null;对于方法参数,使用 ArgumentNullException.ThrowIfNull()

posted @ 2026-08-27 07:54  人生就是修炼  阅读(9)  评论(0)    收藏  举报