不经常但有时我需要使用 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/