Why some identical strings are not interned in .NET?

后端 未结 5 1546
悲&欢浪女
悲&欢浪女 2020-12-21 00:17
string s1 = \"test\";
string s5 = s1.Substring(0, 3)+\"t\"; 
string s6 = s1.Substring(0,4)+\"\";   
Console.WriteLine(\"{0} \", object.ReferenceEquals(s1, s5)); //Fa         


        
5条回答
  •  再見小時候
    2020-12-21 01:17

    From msdn documentation of object.ReferenceEquals here:

    When comparing strings.If objA and objB are strings, the ReferenceEquals method returns true if the string is interned.It does not perform a test for value equality.In the following example, s1 and s2 are equal because they are two instances of a single interned string.However, s3 and s4 are not equal, because although they are have identical string values, that string is not interned.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String s1 = "String1";
          String s2 = "String1";
          Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2));
          Console.WriteLine("{0} interned: {1}", s1, 
                            String.IsNullOrEmpty(String.IsInterned(s1)) ? "No" : "Yes");
    
          String suffix = "A";
          String s3 = "String" + suffix;
          String s4 = "String" + suffix;
          Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4));
          Console.WriteLine("{0} interned: {1}", s3, 
                            String.IsNullOrEmpty(String.IsInterned(s3)) ? "No" : "Yes");
       }
    }
    // The example displays the following output:
    //       s1 = s2: True
    //       String1 interned: Yes
    //       s3 = s4: False
    //       StringA interned: No
    

提交回复
热议问题