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

相关推荐
吃糖的小孩13 小时前
从只读页面到可控真实探针:我如何给 Owner Console 加手动诊断
前端
谷无姜13 小时前
为什么你的性能优化无效?可能是"木桶效应"在作祟
前端·性能优化
噢,我明白了13 小时前
Java中日期和字符串的处理
java·开发语言·日期
雾非雾13 小时前
《基于具身交互智能数字人技术:如何打造AI数字人宣讲平台"红厅智播”》
前端
海盗123413 小时前
微软技术日报 ——2026-07-21
microsoft·c#·.net
dkbnull13 小时前
Spring Boot请求处理组件对比详解
java·spring boot
jun_bai13 小时前
Orthanc服务器使用java上传dicom影像文件
java·运维·服务器
-银雾鸢尾-13 小时前
C#中的泛型约束
开发语言·c#
顺风尿一寸13 小时前
记一次 Spring AOP 与定时任务引发的死锁排查
java
Revolution6113 小时前
一段 JavaScript 代码执行时,到底发生了什么
前端·javascript