相关疑难解决方法(0)

你能通过不安全的方法改变(不可变)字符串的内容吗?

我知道字符串是不可变的,对字符串的任何更改只会在内存中创建一个新字符串(并将旧字符串标记为空闲字符串).但是,我想知道我的下面的逻辑是否合理,你实际上可以以一种循环方式修改字符串的内容.

const string baseString = "The quick brown fox jumps over the lazy dog!";

//initialize a new string
string candidateString = new string('\0', baseString.Length);

//Pin the string
GCHandle gcHandle = GCHandle.Alloc(candidateString, GCHandleType.Pinned);

//Copy the contents of the base string to the candidate string
unsafe
{
    char* cCandidateString = (char*) gcHandle.AddrOfPinnedObject();
    for (int i = 0; i < baseString.Length; i++)
    {
        cCandidateString[i] = baseString[i];
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法确实改变了内容candidateString(没有在内存中创建新的candidateString),还是运行时通过我的技巧看待它并将其视为普通字符串?

c#

14
推荐指数
2
解决办法
1460
查看次数

标签 统计

c# ×1