如果我通过在代码块或方法中使用指针来操作托管 C# 字符串(例如,反转其字符)unsafe
,这种不安全的实现会混淆或破坏 .NET 字符串池机制吗?
被操作的建议字符串是在托管代码中创建的,并传递给要操作的不安全方法。
这种情况的例子:
static void Main(string[] args) {
string s = "this is a test";
UnsafeReverse(s);
Console.WriteLine(s); // displays "tset a si siht"
// assume more managed strings are created and used along with the affected s.
}
static unsafe void UnsafeReverse(string str) {
int len = str.Length;
fixed (char* pStr = str) {
char* p1 = pStr;
char* p2 = pStr + len - 1;
char tmp;
while (p1 < p2) {
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
++p1; --p2;
}
}
}