在 C# 中,既可以通过值也可以通过引用传递参数。
(1).通过引用传递参数允许函数成员(方法、属性、索引器、运算符和构造函数)更改参数的值,并保持该更改。若要通过引用传递参数,请使用 ref 或 out 关键字。
(2).通过值传递值类型,通过值将变量 n 传递给方法 SquareIt。方法内发生的任何更改对变量的原始值无任何影响。
示例:通过值传递值类型
class PassingValByVal
{
static void SquareIt(int x)
// The parameter x is passed by value.
// Changes to x will not 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(n); // Passing the variable by value.
System.Console.WriteLine("The value after calling the method: {0}", n);
}
}
输出:
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 5
示例:通过引用传递值类型
C#
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);
}
}
输出:
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25