String S1 = " Mytest " ;
String S2 = New Stringbuilder (). append ( " My " ). Append ( " Test " ). Tostring ();
String S3 = String . Intern (S2 );
Console. writeline (object) S2 = (Object) S1 ); // Different references.
Console. writeline (object) S3 = (Object) S1 ); // The same reference.
Intern
[In bytes t records: N] V. detention, house arrest N. Intern
The Common Language Runtime library stores strings by maintaining a table calledDetention pool, It containsProgramA reference to each unique string declared or created programmatically. Therefore, there is only one instance of a string with a specific value in the system.
For example, if the same string is assigned to several variables, the runtime will retrieve the same reference to the string from the detention pool and allocate it to each variable.
The intern method uses the detention pool to searchStr
A string with equal values. If such a string exists, it is referenced in the detention pool. If not, add a pair to the detention poolStr
And then return the reference.
In the following C # example, the string S1 with the value of "mytest" is reserved because it is a String constant in the program.
Class to generate a new String object with the same value as S1. References to this string are assigned to S2.
The intern method searches for strings with the same value as S2. Because such a string exists, this method returns the same reference allocated to S1, and then assigns the reference to S3.
The comparison results of referencing S1 and S2 are not equal because they reference different objects, and the comparison results of referencing S1 and S3 are equal, because they reference the same string.