优雅绽放 發表於 2026-1-9 10:48:52

C# string.IsNullOrEmpty和IsNullOrWhiteSpace方法实现

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>IsNullOrEmpty</li><li>IsNullOrWhiteSpace</li><li>主要区别</li><li>使用建议</li><li>注意事项</li></ul></div><p>string.IsNullOrEmpty 和 IsNullOrWhiteSpace 这两个方法的区别和用法</p>
<p class="maodian"></p><h2>IsNullOrEmpty</h2>
<div class="jb51code"><pre class="brush:csharp;">public static bool IsNullOrEmpty(string? value)</pre></div>
<blockquote><p>这个方法检查字符串是否为:</p>
<p>1. null<br />2. 空字符串 (&quot;&quot;)</p></blockquote>
<div class="jb51code"><pre class="brush:csharp;">string str1 = null;
string str2 = "";
string str3 = " ";

Console.WriteLine(string.IsNullOrEmpty(str1));// true
Console.WriteLine(string.IsNullOrEmpty(str2));// true
Console.WriteLine(string.IsNullOrEmpty(str3));// false</pre></div>
<p class="maodian"></p><h2>IsNullOrWhiteSpace</h2>
<div class="jb51code"><pre class="brush:csharp;">public static bool IsNullOrWhiteSpace(string? value)</pre></div>
<blockquote><p>这个方法检查字符串是否为:</p>
<p>1. null<br />2. 空字符串 (&quot;&quot;)<br />3. 只包含空白字符的字符串(空格、制表符、换行符等)</p></blockquote>
<div class="jb51code"><pre class="brush:csharp;">string str1 = null;
string str2 = "";
string str3 = " ";
string str4 = "\t\n\r";
string str5 = " ";// 包含全角空格

Console.WriteLine(string.IsNullOrWhiteSpace(str1));// true
Console.WriteLine(string.IsNullOrWhiteSpace(str2));// true
Console.WriteLine(string.IsNullOrWhiteSpace(str3));// true
Console.WriteLine(string.IsNullOrWhiteSpace(str4));// true
Console.WriteLine(string.IsNullOrWhiteSpace(str5));// true</pre></div>
<p class="maodian"></p><h2>主要区别</h2>
<blockquote><p>检查范围 :</p>
<p>- IsNullOrEmpty 只检查 null 和空字符串<br />- IsNullOrWhiteSpace 还会检查空白字符</p></blockquote>
<blockquote><p>性能 :</p>
<p>- IsNullOrEmpty 性能略好,因为不需要遍历字符串<br />- IsNullOrWhiteSpace 需要遍历字符串来检查空白字符</p></blockquote>
<blockquote><p>使用场景 :</p>
<p>- IsNullOrEmpty 适用于只需要检查字符串是否为空的场景<br />- IsNullOrWhiteSpace 适用于需要验证用户输入或数据清理的场景</p></blockquote>
<p class="maodian"></p><h2>使用建议</h2>
<blockquote><p>- 如果只需要检查字符串是否为 null 或空,使用 IsNullOrEmpty<br />- 如果需要验证用户输入,建议使用 IsNullOrWhiteSpace<br />- 在性能敏感的场景,优先考虑 IsNullOrEmpty<br />- 处理用户界面或数据验证时,优先考虑 IsNullOrWhiteSpace</p></blockquote>
<p class="maodian"></p><h2>注意事项</h2>
<blockquote><p>- 两个方法都是静态方法,需要通过 string. 来调用<br />- 从 C# 8.0 开始,这两个方法支持可空引用类型<br />- 这两个方法都是线程安全的<br />- 在处理大量数据时,性能差异可能会变得明显</p></blockquote>
<p>到此这篇关于C# string.IsNullOrEmpty和IsNullOrWhiteSpace方法实现的文章就介绍到这了,更多相关C# string.IsNullOrEmpty 和 IsNullOrWhiteSpace 内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>C#中IsNullOrEmpty和IsNullOrWhiteSpace的使用方法及区别解析</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: C# string.IsNullOrEmpty和IsNullOrWhiteSpace方法实现