値による引数の受け渡し
デフォルトでは、C#の引数は値で渡されます。これは、メソッドに渡されたときに値のコピーが作成されることを意味します。
class Test
{
static void Foo(int p)
{
p = p + 1; // Increment p by one.
Console.WriteLine(p); // Write p to screen.
}
static void Main()
{
int x = 8;
Foo(x); // Make a copy of x.
Console.WriteLine(x); // x will still be 8.
}
}
pとxは異なるメモリ位置にあるため、pa new valueを割り当てても、変数xの内容は変更されません。
reference-tupe引数を値で渡すと、参照はコピーされますが、オブジェクトはコピーされません。文字列ビルダーの場合の例。ここで、Fooは、StringBuilder
メインがインスタンス化したものと同じオブジェクトを認識しますが、それに対する独立した参照を持っています。したがって、StrBuildとfooStrBuildは、同じStringBuilder
オブジェクトを参照する別個の変数です。
class Test
{
static void Foo(StringBuilder fooStrBuild)
{
fooStrBuild.Append("testing");
fooStrBuild = null;
}
static void Main()
{
StringBuilder StrBuild = new StringBuilder();
Foo(strBuild);
Console.WriteLine(StrBuild.ToString()); // "testing"
}
}
fooStrBuildは参照のコピーであるため、その値を変更してもStrBuildは変更されません。
参照による通過
以下では、pとxは同じメモリ位置を参照しています。
class Test
{
static void Foo(ref int p)
{
p = p + 1; // Increment p by one.
Console.WriteLine(p); // Write p to screen.
}
static void Main()
{
int x = 8;
Foo(ref x); // Make a copy of x.
Console.WriteLine(x); // x is now 9.
}
}
したがって、pの値が変更されます。
お役に立てれば。