栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

string.IsNullOrEmpty(string)与string.IsNullOrWhiteSpace(string)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

string.IsNullOrEmpty(string)与string.IsNullOrWhiteSpace(string)

最佳做法是选择最合适的一种。

.Net framework 4.0 Beta
2为字符串提供了一个新的IsNullOrWhiteSpace()方法,该方法将IsNullOrEmpty()方法推广为除空字符串之外还包括其他空白。

术语“空白”包括屏幕上不可见的所有字符。 例如,空格,换行符,制表符和空字符串是空格字符*。

参考:这里

对于性能而言,IsNullOrWhiteSpace并不理想,但很好。该方法调用将导致较小的性能损失。此外,如果您不使用Unipre数据,则IsWhiteSpace方法本身具有一些可以删除的间接寻址。与往常一样,过早的优化可能是邪恶的,但这也很有趣。

参考:这里

检查源代码 (参考源.NET framework 4.6.2)

IsNullorEmpty

[Pure]public static bool IsNullOrEmpty(String value) {    return (value == null || value.Length == 0);}

IsNullOrWhiteSpace

[Pure]public static bool IsNullOrWhiteSpace(String value) {    if (value == null) return true;    for(int i = 0; i < value.Length; i++) {        if(!Char.IsWhiteSpace(value[i])) return false;    }    return true;}

例子

string nullString = null;string emptyString = "";string whitespaceString = "    ";string nonEmptyString = "abc123";bool result;result = String.IsNullOrEmpty(nullString); // trueresult = String.IsNullOrEmpty(emptyString);// trueresult = String.IsNullOrEmpty(whitespaceString);      // falseresult = String.IsNullOrEmpty(nonEmptyString);        // falseresult = String.IsNullOrWhiteSpace(nullString);       // trueresult = String.IsNullOrWhiteSpace(emptyString);      // trueresult = String.IsNullOrWhiteSpace(whitespaceString); // trueresult = String.IsNullOrWhiteSpace(nonEmptyString);   // false


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575928.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号