• String.IsNullOrWhiteSpace和String.IsNullOrEmpty的区别


    以前刚入行的时候判断字符串的时候用

    string a="a";
    a=="";
    a==null;

    后来发现了String.IsNullOrEmpty感觉方便了好多,但是后来发现如果字符串的空白String a="  ";IsNullOrEmpty就没法判断了,于是我今天发现了String.IsNullOrWhiteSpace,此方法只在framework4.0以上才能使用,官方的解释是:指示指定的字符串是 null、空还是仅由空白字符组成。

    http://msdn.microsoft.com/zh-cn/library/system.string.isnullorwhitespace(v=vs.100).aspx

    string a = null;
                string b = string.Empty;
                string c = "";
                string d = "  ";
                Console.WriteLine("a:{0};
     b:{1};
     c:{2};
     d:{3};
    ", a, b, c, d);
                if (string.IsNullOrEmpty(a))
                    Console.WriteLine("a");
                if (string.IsNullOrEmpty(b))
                    Console.WriteLine("b");
                if (string.IsNullOrEmpty(c))
                    Console.WriteLine("c");
                if (string.IsNullOrEmpty(d))
                    Console.WriteLine("d");
    
                if (string.IsNullOrWhiteSpace(a))
                    Console.WriteLine("a1");
                if (string.IsNullOrWhiteSpace(b))
                    Console.WriteLine("b1");
                if (string.IsNullOrWhiteSpace(c))
                    Console.WriteLine("c1");
                if (string.IsNullOrWhiteSpace(d))
                    Console.WriteLine("d1");
                Console.Read();

    执行结果:

    由此可见当用IsNullOrEmpty时,d是没有输出来的,但是string.IsNullOrWhiteSpace却可以,如果执意要用前者又要判断空白的话,不妨与Trim组合使用。

    [转]https://www.cnblogs.com/tony312ws/p/3727179.html

    另一篇文章分析了源码:https://www.cnblogs.com/songwenjie/p/8657579.html

    表示:IsNullOrWhiteSpace是IsNullOrEmpty的加强

    MSDN说,IsNullOrWhiteSpace性能更高一些,推荐使用。可以测试一下。

  • 相关阅读:
    ffmpeg 合并文件
    win10 设备摄像头,麦克风,【隐私】权限
    负载均衡,过载保护 简介
    《用Python做科学计算》 书籍在线观看
    Getting Started with OpenMP
    Algorithms & Data structures in C++& GO ( Lock Free Queue)
    PostgreSQL新手入门
    Ubuntu 网络配置
    QT 4.7.6 驱动 罗技C720摄像头
    使用vbs脚本添加域网络共享驱动器
  • 原文地址:https://www.cnblogs.com/djd66/p/15247241.html
Copyright © 2020-2023  润新知