问题
I have written a function Reverse to reverse a string in .net using pointers in unsafe context. I do like this.
I allocate “greet” and “x” same value. I reverse greet to my surprise x also gets reversed.
using System;
class Test{
private unsafe static void Reverse(string text){
fixed(char* pStr = text){
char* pBegin = pStr;
char* pEnd = pStr + text.Length - 1;
while(pBegin < pEnd){
char t = *pBegin;
*pBegin++ = *pEnd;
*pEnd-- = t;
}
}
}
public static void Main(){
string greet = "Hello World";
string x = "Hello World";
Reverse(greet);
Console.WriteLine(greet);
Console.WriteLine(x);
}
}
回答1:
Nothing odd about that. You're seeing interning. If you write:
Console.WriteLine(object.ReferenceEquals(greet, x));
immediately after the declaration, you'll see that you've only got one string object. Both your variables refer to the same object, so obviously if you make a modification to the object via one variable, you'll see the same change when you access it later through the other variable.
From the C# 4 spec, section 2.4.4.5:
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 appear in the same program, these string literals refer to the same string instance.
Oh, and I hope that in real code you're not actually modifying strings using unsafe operations...
来源:https://stackoverflow.com/questions/10230772/is-strings-in-net-get-changed-is-there-some-bug