19

コードはかなり自明です。私が作成したときa1b1同じテキストを含む 2 つの異なる文字列インスタンスを作成していると思っていました。したがって、私は正しいと思いますが、間違っていると思いa1 == b1ますが、object.ReferenceEquals(a1,b1)そうではありません。なんで?

//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
4

3 に答える 3

20

リテラル文字列オブジェクトは、コンパイラによって単一のインスタンスに結合されます。これは実際には仕様で必要です:

各文字列リテラルが必ずしも新しい文字列インスタンスになるとは限りません。文字列等値演算子 (セクション 7.9.7) に従って等価である 2 つ以上の文字列リテラルが同じアセンブリに現れる場合、これらの文字列リテラルは同じ文字列インスタンスを参照します。

于 2012-05-28T04:48:33.167 に答える
8

The compiler is optimized to that the if string literals are equal with "==" operator than it does not need to create a new instance and both refer to the same instance... So, that's why your first part of question answered True.

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

string a = "hello";
string b = "h";
// Append to contents of 'b'
b += "ello";
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance.

The + operator concatenates strings:

string a = "good " + "morning";

This creates a string object that contains "good morning".

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

string b = "h";
b += "ello";

for more reference check this on msdn and this

于 2012-05-28T04:58:00.310 に答える
2

コンパイラの最適化。そのような単純な。

于 2012-05-28T04:45:29.223 に答える