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 或空字符串,不考虑字符串中只包含空格的情况。

相关推荐
Hilaku39 分钟前
为什么在 2026 年,MPA(多页面应用)正在悄悄复辟?
前端·javascript·程序员
幸福小宝43 分钟前
eslint和prettier
前端
geovindu43 分钟前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
anyup43 分钟前
终于在今天入选了 Gitee GVP,这真值得庆祝~
前端·uni-app·开源
幸福小宝1 小时前
husky和lint-staged
前端
Slice_cy1 小时前
Mint 自研框架设计与实现:从重复开发走向配置驱动(五)
前端·后端·架构
景同学1 小时前
把 AI 用到线上运维:可行、有效,前提是喂足信息——一次 Full GC 排障实录
java·人工智能·后端
寒水馨1 小时前
Windows下载、安装 Tailwind CSS-v4.3.3(附安装包tailwindcss-windows-x64.exe)
前端·css·前端开发·tailwind css·utility-first·css 框架·独立 cli
西楼_1 小时前
一文读懂React19究竟更新了什么
前端
四眼肥鱼1 小时前
【Nextjs】macos 系统运行报错:Error: Cannot find module '../lightningcss.darwin-x64.node'
前端·架构·前端框架