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

    原文地址:http://www.cnblogs.com/fanyong/archive/2012/11/01/2750163.html

    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[] {
            '	', '
    ', 'v', 'f', '
    ', ' ', 'x0085', 'x00a0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            ' ', ' ', ' ', ' ', '', 'u2028', 'u2029', ' ', ''
         };
     
    }
    

      

     再看一段代码:

    string s1 = "";
    string s2 = string.Empty;
    if (s1 == s2)<br>{
        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)<br>{<br>    if (value != null)
        {
            return (value.Length == 0);
        }
        return true;
    }
    

      

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

  • 相关阅读:
    设置DataGridView垂直滚动条
    在自定义MessageBox控件里添加键盘回车事件。
    通过访问注册表,表判断系统是否装excel
    让文本框里只能输入数字
    新晋菜鸟的错误
    jdbc连接数据库以及crud(简单易懂,本人亲测可用 有源代码和数据库)
    springboot 错误求解决
    maven 导包报错
    最短路径Dijkstra
    读写者问题
  • 原文地址:https://www.cnblogs.com/techfans/p/4498069.html
Copyright © 2011-2022 走看看