0%

【C#】值类型转换关键字“ref”&\"out\"

由于值类型实参传入方法后无法被保存,所以可以用关键字“ref”将其临时“转换”为引用类型。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int age=3;

static int Growth(ref int _age)
{
_age++;
}

Growth(ref age);

Console.WriteLine(age);```

输出结果为4

<strong>需要注意的是,定义形参、传入实参时都要使用关键字“ref”,且不可传入对象的字段,只能传入定义的变量。</strong>

 

 

如果我们想输出一个传入值类型方法的结果,可以使用return来传出。但是如果要传出多个值,就可以使用关键字“out”了
例:

```csharp
int age=3;
static int Growth(int _age,out int lastYear,out int nextYear)
{
lastYear=_age--;
nextYear=_age++;
}
int ly,ny;//设置变量来接收Growth输出的lastYear和nextYear
Growth(age,out ly,out ny);
Console.WriteLine(ly+","+ny);

输出结果为2,4。 对比关键字“ref”可知,使用关键字“out”时也需要定义形参、传入实参时都使用,且传出的值需要定义变量接收。