// PassingParams1.cs using System;class PassingValByVal{ static void SquareIt(int x) // The parameter x is passed by value. // Changes to x will not affect the original value of myInt. { x *= x; Console.WriteLine("The value inside the method: {0}", x); } public static void Main() { int myInt = 5; Console.WriteLine("The value before calling the method: {0}", myInt); SquareIt(myInt); // Passing myInt by value. Console.WriteLine("The value after calling the method: {0}", myInt); }} 输出 The value before calling the method: 5The value inside the method: 25The value after calling the method: 5 代码讨论 变量 myInt 为值类型,包含其数据(值 5)。当调用 SquareIt 时,myInt 的内容被复制到参数 x 中,在方法内将该参数求平方。但在 Main 中,myInt 的值在调用 SquareIt 方法之前和之后是相同的。实际上,方法内发生的更改只影响局部变量 x。
// PassingParams2.cs using System;class PassingValByRef{ static void SquareIt(ref int x) // The parameter x is passed by reference. // Changes to x will affect the original value of myInt. { x *= x; Console.WriteLine("The value inside the method: {0}", x); } public static void Main() { int myInt = 5; Console.WriteLine("The value before calling the method: {0}", myInt); SquareIt(ref myInt); // Passing myInt by reference. Console.WriteLine("The value after calling the method: {0}", myInt); }}