晨鸟科技

 找回密码
 注册
搜索
查看: 9568|回复: 4
打印 上一主题 下一主题

string.Insert方法应该注意其返回值

[复制链接]
跳转到指定楼层
楼主
发表于 2011-2-22 11:02:19 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 Star 于 2011-2-22 11:08 编辑
% d7 t' R* H$ {+ i8 [( ^+ I
& d3 y8 r9 R- O0 O这一久在给EB_EXP debug,有个地方需要对字符串进行Insert处理,原来的程序是这样写的:
  1. 4 i# b) g6 R! R$ Y# G
  2. result.Insert(result.IndexOf("</p>"), " (单位:分钟)");
    . z1 V; ]6 ~# ]5 F6 B  P0 t
复制代码
调试过程中,发现返回的这个result的值没有改变,仍然是执行Insert操作之前的值,于是去网上查,MSDN(http://msdn.microsoft.com/en-us/library/system.string.insert.aspx)上有一条注意说明:
# h& Z7 U# h  {; l" A4 x7 M% z Note  " t+ B4 p" p" b2 V* K% G
   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.
( }  r: Z+ r2 z4 y% I ( S4 t. Q2 \7 W* `7 m( V
看了这句话就知道了,原来string的Insert操作没有修改result的值,所以返回result的话,是不对的,应该返回Insert方法的返回值,如下:

  1.   [; o, i5 m" Y: w: ]
  2. result = result.Insert(result.IndexOf("</p>"), " (单位:分钟)");
    2 W% y' y3 Y) `5 {5 x
复制代码
沙发
 楼主| 发表于 2011-2-28 15:24:49 | 显示全部楼层
回复 xueshuai 的帖子% |: f% w3 ]5 `4 e
囧。。。$ f$ f$ s3 E- J; @

3 [6 W$ o0 d) [4 _4 s6 q   
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|晨鸟科技 ( 沪ICP备09012675号 )

GMT+8, 2024-5-17 15:52 , Processed in 6.077382 second(s), 9 queries , Wincache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表