string.Replace(或其他字符串修改)不起作用 [英] string.Replace (or other string modification) not working
问题描述
对于以下代码,我无法让 string.Replace
工作:
For the following code, I can't get the string.Replace
to work:
someTestString.Replace(someID.ToString(), sessionID);
当我调试和检查参数时,它们有我期望的值 - 即 someID.ToString()
得到1087163075",而 sessionID
有108716308"和 someTestString
包含1087163075".
when I debug and check parameters they have values I expect - i.e. someID.ToString()
got "1087163075", and sessionID
has "108716308" and someTestString
contains "1087163075".
我不知道为什么这不起作用更改 someTestString
完整示例:
string someTestString =
"<a href='myfoldert/108716305-1.jpg' target='_blank'>108716305-1.jpg</a>"
someTestString.Replace("108716305", "NewId42");
结果(在 someTestString
中)应该是这样的:
the result (in someTestString
) should be this:
"<a href='myfoldert/NewId42-1.jpg' target='_blank'>NewId42-1.jpg</a>"
但它没有改变.在点击我的代码后,someTestString
的字符串保持不变.
but it doesn't change. The string for someTestString
remains unchanged after hitting my code.
推荐答案
字符串是不可变的.string.Replace
的结果是一个带有替换值的新字符串.
Strings are immutable. The result of string.Replace
is a new string with the replaced value.
您可以将结果存储在新变量中:
You can either store result in new variable:
var newString = someTestString.Replace(someID.ToString(), sessionID);
或者如果您只想观察字符串更新"行为,则只需重新分配给原始变量:
or just reassign to original variable if you just want observe "string updated" behavior:
someTestString = someTestString.Replace(someID.ToString(), sessionID);
请注意,这适用于所有其他 string
函数,例如 Remove
、Insert
、trim 和 substring 变体 - 它们都返回新字符串作为不能修改原始字符串.
Note that this applies to all other string
functions like Remove
, Insert
, trim and substring variants - all of them return new string as original string can't be modified.
这篇关于string.Replace(或其他字符串修改)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!