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

标签 c#

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

相关文章:

c# - NHibernate SysCache2 和查询缓存 - 无法避免 Select N+1?

c# - 为什么我的文本文件会突然停止保存?

javascript - Web 浏览器控制阻止您确定要离开此页面吗

c# - VS2010拒绝编译命名空间,说它不存在

c# - 检查用户是否第一次使用我的应用程序的某个部分

c# - 覆盖 DLL 中的 DataModel

c# - Wpf 检测窗口何时从另一个窗口关闭

c# - 使用不同域中的 oidc-client 和 identityServer4 登录

c# - NHibernate.Mapping.ByCode.Conformist.ClassMapping 和 FluentNHibernate.Mapping.ClassMap 有什么区别?

c# - 如何检查 XmlAttributeCollection 中是否存在属性?