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

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public static readonly string Empty;
    //这就是String.Empty 那是只读的String类的成员,也是string的变量的默认值是什么呢?
     
    //String的构造函数
    static String(){
        Empty = "";//Empty就是他""
        WhitespaceChars = new char[] {
            ' ', ' ', 'v', 'f', ' ', ' ', 'x0085', 'x00a0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            ' ', ' ', ' ', ' ', '', 'u2028', 'u2029', ' ', ''
         };
     
    }

      

     再看一段代码:

    1
    2
    3
    4
    5
    6
    7
    8
    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未指向任何对象。

    转自http://www.cnblogs.com/fanyong/archive/2012/11/01/2750163.html

  • 相关阅读:
    图的存储结构(精编)
    二叉树的输入
    哈夫曼树及编码
    C. Bits (Codeforces Round #276 (Div. 2) )
    C++ Map 容器
    POJ 1080 Human Gene Functions(dp)
    数和二叉树——二叉树的建立及应用(遍历等)(基础篇)
    数独问题的介绍及POJ 2676-Sudoku(dfs+剪枝)
    【数据结构】——稀疏矩阵转置
    POJ 3083 Children of the Candy Corn
  • 原文地址:https://www.cnblogs.com/AaronBear/p/5679934.html
Copyright © 2011-2022 走看看