2013-03-05 72 views
1

我已经写了一个函数,但是这个函数仍旧返回旧字符串而不是新字符串。我不知道如何当你做了与旧返回一个新值

东西例如返回一个新的字符串:

public string TestCode(string testString) 
{ 

// Here something happens with the testString 


//return testString; <-- i am returning still the same how can i return the new string //where something is happened with in the function above 

} 
+3

我相信你应该考虑发布实际的代码。目前还不清楚“测试串发生了什么”。 – 2013-03-05 09:07:35

回答

5

//这里有事与将TestString

制作当然,你对这个字符串做了什么,你正在把它分配回testString

testString = testString.Replace("A","B"); 

因为字符串是immutable

我假设你调用的函数,如:

string somestring = "ABC"; 
somestring = TestCode(somestring); 
+0

我的不好。它非常不可变,所以我可以将它看作是一种值类型。 (不考虑它,哎呀)。 – Jodrell 2013-03-05 09:35:01

0

String是不变的(即着的改变)。你要做这样的

 myString = TestCode(myString) 
0

只要确认新的字符串值分配给一个变量(或参数testString)。例如,一个非常常见的错误在这里:

testString.Replace("a", ""); // remove the "a"s 

这应该是:

return testString.Replace("a", ""); // remove the "a"s 

testString = testString.Replace("a", ""); // remove the "a"s 
... 
return testString; 

的一点是:string是不可改变的:Replace等不改旧字符串:他们创建了一个需要存储在某个地方的新字符串。