gpt4 book ai didi

c# - 为什么 `String.Trim()` 不修剪对象本身?

转载 作者:太空狗 更新时间:2023-10-29 23:54:07 24 4
gpt4 key购买 nike

不经常但有时我需要使用 String.Trim() 来删除字符串的空格。
如果距离上次修剪编码的时间更长,我会写:

string s = " text ";
s.Trim();

并且惊讶于为什么 s 没有改变。我需要写:

string s = " text ";
s = s.Trim();

为什么一些字符串方法以这种(不是很直观)的方式设计?字符串有什么特别之处吗?

最佳答案

字符串是不可变的。任何字符串操作都会在不改变原始字符串的情况下生成新字符串。

来自 MSDN :

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

关于c# - 为什么 `String.Trim()` 不修剪对象本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10190818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com