C# 返回新值

C# 返回新值,c#,C#,我已经写了一个函数,但是这个函数仍然返回旧字符串而不是新字符串。我不知道如何返回一个新的字符串时,你做了一些旧的 举例来说: 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 //wh

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

举例来说:

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

}
publicstringtestcode(stringteststring)
{
//这里,testString发生了一些事情
//返回testString;
//这里,testString发生了一些事情

确保无论您使用字符串做什么,都会将其重新分配给
testString
like

testString = testString.Replace("A","B");
因为字符串是

我假设您调用的函数如下所示:

string somestring = "ABC";
somestring = TestCode(somestring);
//这里,testString发生了一些事情

确保无论您使用字符串做什么,都会将其重新分配给
testString
like

testString = testString.Replace("A","B");
因为字符串是

我假设您调用的函数如下所示:

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

String
是不可变的(即不能更改)。您必须这样做

      myString = TestCode(myString) 

String
是不可变的(即不能更改)。您必须这样做

      myString = TestCode(myString) 

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

testString.Replace("a", ""); // remove the "a"s
这应该是:

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


要点是:
string
是不可变的:
Replace
等不会更改旧字符串:它们会创建一个新字符串,您需要将其存储在某个地方。

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

testString.Replace("a", ""); // remove the "a"s
这应该是:

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


<> >点:<代码>字符串< /代码>是不可变的:<代码>替换<代码>等,不改变旧字符串:它们创建一个新的,你需要存储在某处。

我相信你应该考虑发布实际代码。不清楚“测试字符串发生了什么”。我相信你应该考虑发布实际代码。“与测试字符串一起发生”。我的不好。它是如此不可变,以至于我能够将其视为值类型。(不考虑它,oops)。我的不好。它是如此不可变,以至于我能够将其视为值类型。(不考虑它,oops)。