标题: string.Insert方法应该注意其返回值 [打印本页] 作者: Star 时间: 2011-2-22 11:02 标题: string.Insert方法应该注意其返回值 本帖最后由 Star 于 2011-2-22 11:08 编辑 # y9 F, b. |# R1 D1 g
( ^# p# P$ ?8 o5 H: {
这一久在给EB_EXP debug,有个地方需要对字符串进行Insert处理,原来的程序是这样写的:
2 S6 p+ {; T. U& h; i6 W( P4 S" W
result.Insert(result.IndexOf("</p>"), " (单位:分钟)");8 |) k9 R0 |9 w' m
复制代码
调试过程中,发现返回的这个result的值没有改变,仍然是执行Insert操作之前的值,于是去网上查,MSDN(http://msdn.microsoft.com/en-us/library/system.string.insert.aspx)上有一条注意说明:- t2 O" V# o I& ^0 N% y
Note ( N9 l) Q! Q* Z' F! f( x* g% x5 }( D, H 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." w0 A6 p" g4 w/ F+ |+ W
6 U9 k2 M8 C% d# b
看了这句话就知道了,原来string的Insert操作没有修改result的值,所以返回result的话,是不对的,应该返回Insert方法的返回值,如下:
% Y8 o1 v0 @8 M# m U4 o2 d' L
result = result.Insert(result.IndexOf("</p>"), " (单位:分钟)"); ' T' b! m6 O/ s% s1 F
复制代码
作者: xueshuai 时间: 2011-2-22 17:08
消灭零回复,还楼主自尊~~;P 作者: Star 时间: 2011-2-28 15:24 回复 xueshuai 的帖子 2 o5 ~! v8 l3 o' J* X4 d# h囧。。。2 o0 U$ Q7 p3 M1 F