传值类型
传递一个值类型的变量时,意味着会生成这个变量的一份拷贝,再传给方法.在方法内对这个值的任何修改
都不会影响到传递的那个变量。如果想更改这个变量的值时,可以使用ref或out关键字。
如下例所示:
class PassingValByRef
{
static void SquareIt(ref int x)
// The parameter x is passed by reference.
// Changes to x will affect the original value of x.
{
x *= x;
System.Console.WriteLine("The value inside the method: {0}", x);
}
static void Main()
{
int n = 5;
System.Console.WriteLine("The value before calling the method: {0}", n);
SquareIt(ref n); // Passing the variable by reference.
System.Console.WriteLine("The value after calling the method: {0}", n);
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25
*/
在这例子中,真正传递的是n的引用,所以在Main中n的值被改变了。