zoukankan      html  css  js  c++  java
  • String.Empty、string=”” 和null的区别

    String.Empty是string类的一个静态常量;

    String.Empty和string=””区别不大,因为String.Empty的内部实现是:

    public static readonly string Empty;
    //这就是String.Empty 那是只读的String类的成员,也是string的变量的默认值是什么呢?
    
    //String的构造函数
    static String(){
        Empty = "";//Empty就是他""
        WhitespaceChars = new char[] {
            '\t', '\n', '\v', '\f', '\r', ' ', '\x0085', '\x00a0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            ' ', ' ', ' ', ' ', '', '\u2028', '\u2029', ' ', ''
         };
    
    }
    

      

     再看一段代码:

    string s1 = "";
    string s2 = string.Empty;
    if (s1 == s2)
    { Console.WriteLine("一模一样!"); } // 结果都是True Console.WriteLine("".Equals(string.Empty)); Console.WriteLine(object.ReferenceEquals(string.Empty, ""));

    既然String.Empty和string=””一样,同样需要占用内存空间,为什么推荐优先使用String.Empty ?

    string.Empty只是让代码好读,防止代码产生歧义,比如说:

    string s = "";  string s = " ";   这个不细心看,很难看出是空字符串还是空格字符。

     

    如果判断一个字符串是否是空串,使用

    if(s==String.Empty)和if(s==””)的效率是一样的,但是最高效的写法是if(s.Length==0)

    string.IsNullOrEmpty的内部实现方式:

    public static bool IsNullOrEmpty(string value)
    {
    if (value != null) { return (value.Length == 0); } return true; }

       

    而string str=null则是表示str未指向任何对象。

  • 相关阅读:
    win7下的vxworks总结
    ubuntu 无法获得锁 /var/lib/dpkg/lock
    项目中用到了的一些批处理文件
    win7下安装 WINDRIVER.TORNADO.V2.2.FOR.ARM
    使用opencv统计视频库的总时长
    January 05th, 2018 Week 01st Friday
    January 04th, 2018 Week 01st Thursday
    January 03rd, 2018 Week 01st Wednesday
    January 02nd, 2018 Week 01st Tuesday
    January 01st, 2018 Week 01st Monday
  • 原文地址:https://www.cnblogs.com/fanyong/p/2750163.html
Copyright © 2011-2022 走看看