gpt4 book ai didi

c# - 字符串上的 ReferenceEquals

转载 作者:行者123 更新时间:2023-11-30 20:40:44 26 4
gpt4 key购买 nike

如图所示 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

与 mono(版本 4.0.2)相反,它给出了

True

参见working example .

最佳答案

String.ToString() 返回对同一字符串的引用:

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) 方法。

关于c# - 字符串上的 ReferenceEquals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32972314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com