gpt4 book ai didi

c# - 两个不同的 "strings"是同一个对象实例吗?

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:16 25 4
gpt4 key购买 nike

代码很容易解释。当我制作 a1b1 时,我预计我会创建两个包含相同文本的不同字符串实例。所以我认为 a1 == b1 会是 true 但 object.ReferenceEquals(a1,b1) 会是 false,但事实并非如此。为什么?

//make two seemingly different string instances
string a1 = "test";
string b1 = "test";
Console.WriteLine(object.ReferenceEquals(a1, b1)); // prints True. why?

//explicitly "recreating" b2
string a2 = "test";
string b2 = "tes";
b2 += "t";
Console.WriteLine(object.ReferenceEquals(a2, b2)); // prints False

//explicitly using new string constructor
string a3 = new string("test".ToCharArray());
string b3 = new string("test".ToCharArray());
Console.WriteLine(object.ReferenceEquals(a3, b3)); // prints False

最佳答案

编译器将文字字符串对象合并为单个实例。这实际上是 required by the specification :

Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.

关于c# - 两个不同的 "strings"是同一个对象实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43867973/

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