更新时间:2023-02-17 13:33:11
文字字符串对象都合并为编译器的单实例。这实际上是通过规范需要:
每个字符串不一定产生新的字符串实例。当两个或多个字符串,根据字符串相等运算符(第7.9.7)是等效的出现在同一个组件,这些字符串引用相同的字符串实例。
块引用>The code is pretty self explanatory. I expected when I made
a1
andb1
that I was creating two different string instances that contain the same text. So I figurea1 == b1
would be true butobject.ReferenceEquals(a1,b1)
would be false, but it isn't. Why?//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
Literal string objects are coalesced into single instances by the compiler. This is actually 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.