IsNullOrEmpty和IsNullOrWhiteSpace的区别

IsNullOrEmpty和IsNullOrWhiteSpace的区别

「Talk is cheap. Show me the code」

    string strNull = null;
    string strEmpty = string.Empty;
    string space = "";
    string spaces = "   ";  

    Console.WriteLine("---- IsNullOrEmpty  Start ----");
    Console.WriteLine("IsNullOrEmpty(null): {0}", string.IsNullOrEmpty(strNull));
    Console.WriteLine("IsNullOrEmpty(string.Empty): {0}", string.IsNullOrEmpty(strEmpty));
    Console.WriteLine("IsNullOrEmpty(\"\"): {0}", string.IsNullOrEmpty(""));
    Console.WriteLine("IsNullOrEmpty(\"   \"): {0}", string.IsNullOrEmpty("   "));
    Console.WriteLine("---- IsNullOrEmpty  End ----");

    Console.WriteLine();
    Console.WriteLine();

    Console.WriteLine("---- IsNullOrWhiteSpace  Start ----");
    Console.WriteLine("IsNullOrWhiteSpace(null): {0}", string.IsNullOrWhiteSpace(strNull));
    Console.WriteLine("IsNullOrWhiteSpace(string.Empty): {0}", string.IsNullOrWhiteSpace(strEmpty));
    Console.WriteLine("IsNullOrWhiteSpace(\"\"): {0}", string.IsNullOrWhiteSpace(""));
    Console.WriteLine("IsNullOrWhiteSpace(\"   \"): {0}", string.IsNullOrWhiteSpace("   "));
    Console.WriteLine("---- IsNullOrEmpty  End ----");
    Console.ReadKey();

输出结果:

---- IsNullOrEmpty  Start ----
IsNullOrEmpty(null): True
IsNullOrEmpty(string.Empty): True
IsNullOrEmpty(""): True
IsNullOrEmpty("   "): False
---- IsNullOrEmpty  End ----


---- IsNullOrWhiteSpace  Start ----
IsNullOrWhiteSpace(null): True
IsNullOrWhiteSpace(string.Empty): True
IsNullOrWhiteSpace(""): True
IsNullOrWhiteSpace("   "): True
---- IsNullOrEmpty  End ----

IsNullOrEmpty IsNullOrWhiteSpace
null true true
string.Empty true true
"" true true
" " false true

String.IsNullOrEmpty

String.IsNullOrEmpty 方法 (String)

指示指定的字符串是 null 还是 Empty 字符串。

IsNullOrEmpty是一种便利方法,可用于同时测试String是否是null或其值为Empty。 它等效于以下代码︰

	result = s == null || s == String.Empty;

String.IsNullOrWhiteSpace

String.IsNullOrWhiteSpace 方法 (String)

指示指定的字符串是 null、空还是仅由空白字符组成。

IsNullOrWhiteSpace是具有类似于下面的代码,只不过它提供优越性能的便捷方法︰

	return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
posted @   大志若愚  阅读(11498)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示