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

相关推荐
还有你Y16 小时前
Shell 脚本语法
前端·语法·sh
踩着两条虫18 小时前
如何评价VTJ.PRO?
前端·架构·ai编程
MY_TEUCK19 小时前
Sealos 平台部署实战指南:结合 Cursor 与版本发布流程
java·人工智能·学习·aigc
Mh19 小时前
鼠标跟随倾斜动效
前端·css·vue.js
我爱cope19 小时前
【从0开始学设计模式-10| 装饰模式】
java·开发语言·设计模式
rockey62719 小时前
AScript函数体系详解
c#·.net·script·eval·expression·function·动态脚本
朝新_20 小时前
【Spring AI 】图像与语音模型实战
java·人工智能·spring
小码哥_常20 小时前
Kotlin类型魔法:Any、Unit、Nothing 深度探秘
前端
RH23121120 小时前
2026.4.16Linux 管道
java·linux·服务器
zmsofts20 小时前
java面试必问13:MyBatis 一级缓存、二级缓存:从原理到脏数据,一篇讲透
java·面试·mybatis