变量传递中的ref, out
date
Aug 9, 2022
slug
10025
status
Published
tags
C#
summary
type
Post
By value (this is the default): Think of these as being in-only.
By reference as a ref parameter: Think of these as being in-and-out.
As an out parameter: Think of these as being out-only.
在一个类文件Person.cs里定义一个方法:
public void PassingParameters(int x, ref int y, out int z)
{
// out parameters cannot have a default
// AND must be initialized inside the method
z = 99;
// increment each parameter
x++;
y++;
z++;
}
在Program.cs的main方法里面调用
int a = 10;
int b = 20;
int c = 30;
WriteLine($"Before: a = {a}, b = {b}, c = {c}");
bob.PassingParameters(a, ref b, out c);
WriteLine($"After: a = {a}, b = {b}, c = {c}");
输出为:
Before: a = 10, b = 20, c = 30
After: a = 10, b = 21, c = 100
看到,默认传递a没有改变,ref传递由于传递了引用所以b的值变了,out传递则直接使用的方法内部的值99.
- When passing a variable as a parameter by default, its current value gets passed, not the variable itself. Therefore, x has a copy of the value of the a variable. The a variable retains its original value of 10.
- When passing a variable as a ref parameter, a reference to the variable gets passed into the method. Therefore, y is a reference to b. The b variable gets incremented when the y parameter gets incremented.
- When passing a variable as an out parameter, a reference to the variable gets passed into the method. Therefore, z is a reference to c. The value of the c variable gets replaced by whatever code executes inside the method. We could simplify the code in the Main method by not assigning the value 30 to the c variable since it will always be replaced anyway.
C#7.0之后,可以直接在调用的时候申明out传递
int d = 10;
int e = 20;
WriteLine($"Before: d = {d}, e = {e}, f doesn't exist yet!");
// simplified C# 7.0 or later syntax for the out parameter
bob.PassingParameters(d, ref e, out int f);
WriteLine($"After: d = {d}, e = {e}, f = {f}");