C# 中判空方法 string.IsNullOrEmpty() 和 string.IsNullOrWhiteSpace() 区别

C# 中,string.IsNullOrEmptystring.IsNullOrWhiteSpace 是用于检查字符串是否为空的两种不同方法。

  1. string.IsNullOrEmpty 方法检查字符串是否为 null 或空字符串。如果传入的字符串为 null 或长度为 0,则返回 true;否则返回 false

    csharp 复制代码
    string str = ""; // 或者 string str = null;
    if (string.IsNullOrEmpty(str))
    {
        // 字符串为空或者为null
    }
  2. string.IsNullOrWhiteSpace 方法检查字符串是否为 null、空字符串或者只包含空格。如果传入的字符串为 null、长度为 0 或者只包含空格,则返回 true;否则返回 false

    csharp 复制代码
    string str = "   "; // 或者 string str = null; 或者 string str = "";
    if (string.IsNullOrWhiteSpace(str))
    {
        // 字符串为空、为null或只包含空格
    }

区别在于 string.IsNullOrWhiteSpace 还会将字符串中仅包含空格的情况视为空,而 string.IsNullOrEmpty 仅检查是否为 null 或空字符串,不考虑字符串中只包含空格的情况。

相关推荐
2501_9481069110 分钟前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
TanYYF11 分钟前
spring ai入门教程二
java·人工智能·spring
SeeYa-J24 分钟前
Spring IOC(Inversion of Control)
java·spring·rpc
kyriewen25 分钟前
我筛了 1400 个 Claude Code Skills,留下 5 个天天在用的
前端·ai编程·claude
JNX_SEMI40 分钟前
AT2401C 2.4GHz 全集成射频前端单芯片技术解析
前端·单片机·嵌入式硬件·物联网·硬件工程
不会c+1 小时前
02-SpringBoot配置文件
java·spring boot·后端
anOnion1 小时前
Agentic 前端开发之 实时显示 AI Agent 终端输出
前端·javascript·人工智能
AI 大模型学习不踩坑1 小时前
OpenClaw 完整教程:从安装到使用(官方脚本版)
java·人工智能·神经网络·机器学习·计算机视觉·自然语言处理·openclaw
随风一样自由1 小时前
【前端领域】2026最新前端领域全梳理(框架/工具/AI/跨端/底层标准/就业趋势)
前端·人工智能·前端框架
这是个栗子1 小时前
【前端性能优化】优化数据加载:用 Promise.all 从串行到并行
前端·javascript·性能优化·异步编程·前端优化·promise.all