メソッドに文字列変数を渡しています。私は文字列が参照型であることを知っていますが、メソッド内で割り当てる値は失われます。メソッド内の参照型(文字列)を変更する
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" !?
}
とにかく、これは配列などでは起こりません。誰かが理由を説明することはできますか?
の可能重複(HTTP [値渡し間で異なるとC#を使用して参照することによって通過しているもの]:あなたは方法で変更できるようにあなたは、変数を渡す
ref
キーワードを使用。 //stackoverflow.com/questions/1293111/what-is-different-between-passing-by-value-and-passing-by-reference-using-c) – LBushkin
修正された文字列をTestMethodに返すことはできませんか? –