标题: string.Insert方法应该注意其返回值 [打印本页] 作者: Star 时间: 2011-2-22 11:02 标题: string.Insert方法应该注意其返回值 本帖最后由 Star 于 2011-2-22 11:08 编辑 % B: V/ B9 R, |) h) i* H ( T, T. u0 a t这一久在给EB_EXP debug,有个地方需要对字符串进行Insert处理,原来的程序是这样写的:
0 m6 Z- c3 a+ t& ^0 K
result.Insert(result.IndexOf("</p>"), " (单位:分钟)");7 ^5 t$ n' k% p* R* w) e4 [0 m
复制代码
调试过程中,发现返回的这个result的值没有改变,仍然是执行Insert操作之前的值,于是去网上查,MSDN(http://msdn.microsoft.com/en-us/library/system.string.insert.aspx)上有一条注意说明: 9 M9 {2 |, R0 D; L, N* |9 Y: `& W5 L Note n6 z+ v* Z; A, y. D This method does not modify the value of the current instance. Instead, it returns a new string in which value is inserted into the current instance.6 T& x0 L2 j3 C4 M" L* G' ^" e3 K0 E
4 J- B9 ?* L' K: ?4 o5 g看了这句话就知道了,原来string的Insert操作没有修改result的值,所以返回result的话,是不对的,应该返回Insert方法的返回值,如下:
/ Y% X. A, H- N! W" y& E
result = result.Insert(result.IndexOf("</p>"), " (单位:分钟)");. d# S0 K& C7 u/ d2 O