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

在 C# 中,string.IsNullOrEmpty 和 string.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 或空字符串,不考虑字符串中只包含空格的情况。

相关推荐
步行cgn6 分钟前
MySQL 报错:Access denied for user ‘root‘@‘localhost‘ 详解
java·数据库·spring
颜进强13 分钟前
26 · NestJS 基础篇 · 全专栏总结:五个阶段,一次收拢
前端·后端·ai编程
风寄巴山秋14 分钟前
OpenBMC:Web 页面功能异常排查
运维·服务器·前端·架构
程序员Sunday41 分钟前
Promise.all、allSettled、race、any 怎么选,失败后其他请求会怎样
开发语言·前端·javascript
一个有温度的技术博主41 分钟前
深拷贝和浅拷贝:一次“搬家”事故
java·后端
niucloud-admin42 分钟前
JAVA V6 多商户商城 开发文档——管理端前端
前端
weixin_422201301 小时前
如何解决小程序图标点击热区小,落点不准问题?
前端·小程序·样式·点击热区·扩大
程序员清风1 小时前
AI时代建议学点自己真正感兴趣的!
java·后端·面试
Wang's Blog1 小时前
Java框架 SpringCloud 快速入门: Nacos 配置热更新
java·spring·spring cloud
西索斯coding1 小时前
Kimi k2.7-code-highspeed 接入 Cline 教程:baseURL 路由变更 + model_id 正确写法
java·服务器·数据库·ai