c#中out和ref使用小结
1、out必须在函数体内初始化,在外面初始化没意义。也就是说,out型的参数在函数体内不能得到外面传进来的初始值。
2、ref必段在函数体外初始化。
3、两都在函数体的任何修改都将影响到外面
ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。
使用ref前必须对变量赋值,out不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
区别可以参看下面的代码:
2、ref必段在函数体外初始化。
3、两都在函数体的任何修改都将影响到外面
ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。
使用ref前必须对变量赋值,out不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
区别可以参看下面的代码:
1
using system;
2
class testapp
3
{
4
static void outtest(out int x, out int y)
5
{/离开这个函数前,必须对x和y赋值,否则会报错。
6
/y = x;
7
/上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
8
x = 1;
9
y = 2;
10
}
11
static void reftest(ref int x, ref int y)
12
{
13
x = 1;
14
y = x;
15
}
16
public static void main()
17
{
18
/out test
19
int a,b;
20
/out使用前,变量可以不赋值
21
outtest(out a, out b);
22
console.writeline("a={0};b={1}",a,b);
23
int c=11,d=22;
24
outtest(out c, out d);
25
console.writeline("c={0};d={1}",c,d);
26
27
/ref test
28
int m,n;
29
/reftest(ref m, ref n);
30
/上面这行会出错,ref使用前,变量必须赋值
31
32
int o=11,p=22;
33
reftest(ref o, ref p);
34
console.writeline("o={0};p={1}",o,p);
35
}
36
}
37
using system;2
class testapp3
{4
static void outtest(out int x, out int y)5
{/离开这个函数前,必须对x和y赋值,否则会报错。 6
/y = x; 7
/上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行 8
x = 1;9
y = 2;10
}11
static void reftest(ref int x, ref int y)12
{ 13
x = 1;14
y = x;15
}16
public static void main()17
{18
/out test19
int a,b;20
/out使用前,变量可以不赋值21
outtest(out a, out b);22
console.writeline("a={0};b={1}",a,b);23
int c=11,d=22;24
outtest(out c, out d);25
console.writeline("c={0};d={1}",c,d);26

27
/ref test28
int m,n;29
/reftest(ref m, ref n); 30
/上面这行会出错,ref使用前,变量必须赋值31

32
int o=11,p=22;33
reftest(ref o, ref p);34
console.writeline("o={0};p={1}",o,p);35
}36
} 37




浙公网安备 33010602011771号