4

如果我通过在代码块或方法中使用指针来操作托管 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;
        }
    }
}
4

1 回答 1

6

当然。就这样写来看看伤害:

    static readonly string DontMessWithStrings = "this is a test";

    static void Main(string[] args) {
        string s = "this is a test";
        UnsafeReverse(s);
        Console.WriteLine(DontMessWithStrings);
    }

[由 OP 编辑​​] 显示的结果DontMessWithStrings“tset a si siht”,即使字符串操作代码从未直接触及该变量!

于 2013-05-23T01:10:50.547 回答