向方法传递一个实参时,对应的形参会用实参的一个副本来初始化,不管形参是值类型(例如 int),可空类型(int?),还是引用类型,这一点都是成立的。也就是随便在方法内部进行什么修改,都不会影响实参的值。例如,对于引用类型,方法的改变,只是会改变引用的数据,但实参本身并没有变化,它仍然引用同一个对象。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ref_out
{
class
Program
{
static
void
Main(
string
[] args)
{
int
i = 8;
Console.WriteLine(i);
DoIncrease(i);
Console.WriteLine(i);
}
static
void
DoIncrease(
int
a)
{
a++;
}
}
}
|
运行结果如下:
若使用 ref 关键字,向形参应用的任何操作都同样应用于实参,因为形参和实参引用的是同一个对象。
PS:实参和形参都必须附加 ref 关键字做为前缀。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ref_out
{
class
Program
{
static
void
Main(
string
[] args)
{
int
i = 8;
Console.WriteLine(i);
// 8
DoIncrease(
ref
i);
// 实参前也必须加 ref
Console.WriteLine(i);
// 9 // ref 关键字使对形参的动作也应用于实参
}
static
void
DoIncrease(
ref
int
a)
// 形参前必须加 ref
{
a++;
}
}
}
|
运行结果如下
ref 实参使用前也必须初始化,否则不能通过编译。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ref_out
{
class
Program
{
static
void
Main(
string
[] args)
{
int
i;
// ref 实参没有初始化,所以程序不能通过编译
Console.WriteLine(i);
DoIncrease(
ref
i);
Console.WriteLine(i);
}
static
void
DoIncrease(
ref
int
a)
{
a++;
}
}
}
|
有时我们希望由方法本身来初始化参数,这时可以使用 out 参数。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ref_out
{
class
Program
{
static
void
Main(
string
[] args)
{
int
i;
// 没有初始化
//Console.WriteLine(i); // 此处 i 未初始化,编译错误
DoIncrease(
out
i);
// 用方法来给实参赋初值
Console.WriteLine(i);
}
static
void
DoIncrease(
out
int
a)
{
a = 8;
// 在方法中进行初始化
a++;
// a = 9
}
}
}
|
没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。
本文转自wenglabs博客园博客,原文链接:http://www.cnblogs.com/arxive/p/5948021.html
,如需转载请自行联系原作者