我正在将一个字符串变量传递给一个方法。我知道字符串是引用类型,但我在方法中分配的值丢失了。
public static void TestMethod(string myString)
{
myString = "world";
}
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(s); // output is "hello"
TestMethod(s);
Console.WriteLine(s); // output is also "hello" not "world" !?
}
无论如何,这不会发生在数组中。有人可以解释为什么可能是原因吗?
最佳答案
因为 myString = "world"
为参数分配了一个新字符串,而不是更新现有字符串。要更新对字符串的原始引用,您必须使用 ref
传递参数。
public static void TestMethod(ref string myString)
{
myString = "world";
}
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(s); // output is "hello"
TestMethod(ref s);
Console.WriteLine(s); // output is also "hello" not "world" !?
}
关于c# - 在方法中更改引用类型(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317302/