在第一种情况下Add
返回 x + y。在第二种情况下Add
返回 20 + 40;
当你在函数中赋值时,你改变了变量的本地副本。不是实际值。
例如:
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
int y = 20;
Console.WriteLine(Add(x, y));
// x is still 2, y is still 20
}
static int Add(int x, int y)
{
int ans = x + y;
// You calculate the parameters and store it in the local variable
x = 20;
y = 40;
// You've adapted your local COPIES of the variables
return ans;
// You return the answer which was calculated earlier
}
}
但是,这是因为您正在处理值类型 ( struct
)。如果您正在处理引用类型(class
),那么这是另一回事,例如:
using System;
class Program
{
private class Numbers
{
public int X;
public int Y;
}
static void Main(string[] args)
{
Numbers num = new Numbers();
num.x = 2;
num.y = 20;
Console.WriteLine(Add(num)); // Prints 2 + 20 = 22
// num.x is now 20, and num.y is now 40
Console.WriteLine(Add(num)); // Prints 20 + 40 = 60
}
static int Add(Numbers num)
{
int ans = num.x + num.y;
// You calculate the result from the public variables of the class
num.x = 20;
num.y = 40;
// You change the values of the class
return ans;
// You return the answer which was calculated earlier
}
}
在 C# 中有 4 种“类型”的传递参数:
- 按值传递值类型 (
struct
)。
- 按值传递引用类型 (
class
)。
- 通过引用传递值类型。
- 通过引用传递引用类型。
演示这 4 个的简短示例:
static void Main()
{
int x = 5; // Value type
List<int> list = new List<int>(new [] { 1, 2, 3 }); // Reference type
ValueByValue(x); // x is still 5
ReferenceByValue(list) // list still contains { 1, 2, 3 }
ValueByReference(ref x); // x is now 10
ReferenceByReference(ref list); // list is now a new list containing only { 4, 5, 6 }
}
static void ValueByValue(int x)
{
x = 10; // Changes local COPY of x
}
static void ReferenceByValue(List<int> list)
{
list = new List<int>(new [] { 4, 5, 6 }); // Changes local COPY of list
}
static void ValueByReference(ref int x)
{
x = 10; // Changes the actual x variable in the Main method
}
static void ReferenceByReference(ref List<int> list)
{
list = new List<int>(new [] { 4, 5, 6 }); // Changes the actual list in the Main method
}