c#字符串不变性和string.replace()
> C#开发人员的混淆来源是String.Replace()
>方法的行为。 许多人希望它会修改原始字符串,但事实并非如此。 这是因为c#中的字符串是不可变的。
>假设您想通过"C:\Users\Desktop\Project\bin\Debug"
替换"C:\Users\Desktop\Project\Resources\People"
>将"\bin\Debug"
>更改为"\Resources\People"
>。 尝试:
path.Replace(@"\bin\Debug", @"\Resource\People");
path.Replace("\bin\Debug", "\Resource\People");
将无法更改原始path
字符串。 原因? String.Replace()
> 返回一个带有替换的新字符串;它不会改变原始。
解决方案:重新分配
正确使用String.Replace()
>,您必须将返回的修改后字符串分配给一个变量:
<code class="language-csharp">string path = "C:\Users\Desktop\Project\bin\Debug"; string newPath = path.Replace("\bin\Debug", "\Resources\People"); // newPath now holds the modified string.</code>
<code class="language-csharp">path = path.Replace("\bin\Debug", "\Resources\People"); // path now holds the modified string.</code>
理解不变性
这种行为源于c#中字符串的基本不变性。 似乎修改字符串的任何操作实际上都会创建一个新的字符串对象。这适用于所有字符串方法,影响内存管理。 C#文档清楚地说明了这一特征。 在使用字符串时,请记住这一点。以上是为什么String.Replace在C#中修改我的字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!