ReferenceEquals 字符串

ReferenceEquals on strings

如上所示 here,运行时创建的字符串不能被驻留。

但是,下面的代码:

    class Program {
    static void Main(string[] args)
    {
        string s1 = "Programming Is Fun";
        string s3 = s1.ToString();
        Console.WriteLine(Object.ReferenceEquals(s1, s3));
    }
}

给出(VS 2015):

True

那么,是否以某种方式指定了在运行时生成哪些字符串?

顺便说一句:

代码:

using System;
using System.Text;

class Program {
  static void Main(string[] args)
  {
    string s1 = "hop";
    StringBuilder s2 = new StringBuilder(s1);
    string s3 = s2.ToString();
    Console.WriteLine(Object.ReferenceEquals(s1, s3));
  }
}

给出(VS 2015):

False

与单声道(版本 4.0.2)相反,它给出

True

参见 working example

String.ToString() returns 引用相同的字符串:

public override String ToString() {
    Contract.Ensures(Contract.Result<String>() != null);
    Contract.EndContractBlock();
    return this;
}

并且可以保留在运行时创建的字符串。引自您提到的MSDN article

the runtime does not guarantee that strings created at runtime are interned

驻留是一项昂贵的操作,通常在运行时进行它的成本太高。如果你想确保你的字符串是驻留的,你可以使用 public static String Intern(String str) 方法。