按值传递参数
默认情况下,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.
}
}
为 pa 分配新值不会改变变量 x 的内容,因为 p 和 x 位于不同的内存位置。
按值传递引用元组参数会复制引用,但不会复制对象。字符串生成器的示例;这里 Foo 看到与StringBuilder
main 实例化的对象相同的对象,但对它有一个独立的引用。所以 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 的值发生了变化。
希望这可以帮助。