简体   繁体   English

Reference等于字符串

[英]ReferenceEquals on strings

As indicated here , a string that is created at runtime cannot be interned. 如图所示这里 ,在运行时创建一个字符串不能被拘留。

However, the following code: 但是,以下代码:

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

gives (VS 2015): 给(VS 2015):

True

So, is it specified somehow which strings are generated in runtime? 因此,是否以某种方式指定了在运行时生成哪些字符串?

BTW: BTW:

The code: 编码:

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));
  }
}

gives (VS 2015): 给(VS 2015):

False

in opposite to mono (ver. 4.0.2) which gives 与单声道(版本4.0.2)相反

True

see the working example . 请参阅工作示例

String.ToString() returns reference to the same string: String.ToString()返回对相同字符串的引用:

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

And strings created at runtime can be interned. 并且可以在运行时创建字符串。 Quote from the MSDN article you referred to: 引用您所引用的MSDN文章

the runtime does not guarantee that strings created at runtime are interned 运行时不保证可以对运行时创建的字符串进行实习

Interning is an expensive operation, usually it's too expensive to do it at runtime. 实习是一项昂贵的操作,通常在运行时执行它过于昂贵。 If you want to make sure your string is interned, you can use public static String Intern(String str) method. 如果要确保您的字符串是实习生,可以使用public static String Intern(String str)方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM