更改方法内的引用类型(字符串)

use*_*371 4 c# oop

我将字符串变量传递给方法.我知道字符串是引用类型,但我在方法中分配的值丢失了.

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" !?
}
Run Code Online (Sandbox Code Playgroud)

无论如何,例如,数组不会发生这种情况.有人可以解释为什么可能是原因吗?

Alb*_*nbo 8

因为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" !?
}
Run Code Online (Sandbox Code Playgroud)