晨鸟科技

标题: string.Insert方法应该注意其返回值 [打印本页]

作者: Star    时间: 2011-2-22 11:02
标题: string.Insert方法应该注意其返回值
本帖最后由 Star 于 2011-2-22 11:08 编辑 ) y  t0 V* s. a, J

' `) Z- k. |. _6 {/ \! ]这一久在给EB_EXP debug,有个地方需要对字符串进行Insert处理,原来的程序是这样写的:

  1. + K% M' g$ E2 h/ `' w; U. s" a
  2. result.Insert(result.IndexOf("</p>"), " (单位:分钟)");
    9 Y; K) l) h  p/ b5 l$ m" b* l* w: T
复制代码
调试过程中,发现返回的这个result的值没有改变,仍然是执行Insert操作之前的值,于是去网上查,MSDN(http://msdn.microsoft.com/en-us/library/system.string.insert.aspx)上有一条注意说明:' T% E1 C7 D, P' y& S- b- b/ K. f
Note  3 B4 S1 u( K- h6 k  u
   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." X/ n. O2 `7 G0 ?; K) A
. R$ [0 j* n0 j. H6 ~4 a3 y" _
看了这句话就知道了,原来string的Insert操作没有修改result的值,所以返回result的话,是不对的,应该返回Insert方法的返回值,如下:
  1. ! s9 e; |' J0 w4 w% E
  2. result = result.Insert(result.IndexOf("</p>"), " (单位:分钟)");
    * C2 Z' x- U3 h
复制代码

作者: xueshuai    时间: 2011-2-22 17:08
消灭零回复,还楼主自尊~~;P
作者: Star    时间: 2011-2-28 15:24
回复 xueshuai 的帖子
2 p& O) B7 u- \5 u+ ^( v囧。。。
1 h% M- o5 I; t4 I3 Q0 ^$ B& z- U% _5 \# r5 p* }
   




欢迎光临 晨鸟科技 (http://www.chenniao.com/cprofessor/) Powered by Discuz! X3.2