簡體   English   中英

為什么字符串實習但有不同的引用?

[英]Why string interned but has different references?

string s1 = "abc";
string s2 = "ab";
string s3 = s2 + "c";

Console.WriteLine(string.IsInterned(s3));           // abc
Console.WriteLine(String.ReferenceEquals(s1, s3));  // False

我只是不明白為什么s3實習,但是ReferenceEquals是假的。

他們在實習池中有兩份副本嗎?

提前致謝。

它們是單獨的參考。 字符串"abc"是實體,因為它是文字字符串。

表達式s2 + "c"被編譯為string.Concat(s2, "c") ..這導致一個新的(和單獨的)字符串引用。

這是因為雖然該字符串的值確實被實現(因為文字“abc”),但它與實習字符串不是同一個實例,而是由+運算符生成的實例。

String.ReferenceEquals(s1, string.IsInterned(s3));

會回歸真實

調用string.IsInterned時,基本上有三種不同的情況。 為了說明,這是一個測試方法:

static void MyInternCheck(string str)
{
  var test = string.IsInterned(str);

  if ((object)test == (object)str)
    Console.WriteLine("Yes, your string instance is in the intern pool");
  else if (test == str)
    Console.WriteLine("An instance with the same value exists in the intern pool, but you have a different instance with that value");
  else if (test == null)
    Console.WriteLine("No instance with that value exists in the intern pool");
  else
    throw new Exception("Unexpected intern pool answer");
}

您可以使用以下代碼“命中”所有三種情況:

static void Main()
{
  string x = "0";
  MyInternCheck(x);
  string y = (0).ToString(CultureInfo.InvariantCulture);
  MyInternCheck(y);
  string z = (1).ToString(CultureInfo.InvariantCulture);
  MyInternCheck(z);
}

輸出:

Yes, your string instance is in the intern pool
An instance with the same value exists in the intern pool, but you have a different instance with that value
No instance with that value exists in the intern pool

由於文字"0"在程序文本中提到,與值的字符串例如"0"將在實習生池存在。 變量x是對該實例的引用。

變量yx具有相同的 ,但是直到運行時才計算(C#編譯器沒有猜測int.ToString(IFormatProvider)可能返回的內容)。 因此, y是另一個實例,而不是x

變量z具有在實習池中找不到的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM