c#中out和ref的使用区别
2009-10-30 12:37
417 查看
c#中out和ref的使用区别
ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。使用ref前必须对变量赋值,out不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
如果你想返回多个值怎么办,OUT....
区别可以参看下面的代码:
using
system;
class
testapp
{
static
void
outtest(
out
int
x,
out
int
y)
{
//
离开这个函数前,必须对x和y赋值,否则会报错。
//
y = x;
//
上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
x
=
1
;
y
=
2
;
}
static
void
reftest(
ref
int
x,
ref
int
y)
{
x
=
1
;
y
=
x;
}
public
static
void
main()
{
//
out test
int
a,b;
//
out使用前,变量可以不赋值
outtest(
out
a,
out
b);
console.writeline(
"
a={0};b={1}
"
,a,b);
int
c
=
11
,d
=
22
;
outtest(
out
c,
out
d);
console.writeline(
"
c={0};d={1}
"
,c,d);
//
ref test
int
m,n;
//
reftest(ref m, ref n);
//
上面这行会出错,ref使用前,变量必须赋值
int
o
=
11
,p
=
22
;
reftest(
ref
o,
ref
p);
console.writeline(
"
o={0};p={1}
"
,o,p);
}
}
ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。使用ref前必须对变量赋值,out不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
如果你想返回多个值怎么办,OUT....
区别可以参看下面的代码:
using
system;
class
testapp
{
static
void
outtest(
out
int
x,
out
int
y)
{
//
离开这个函数前,必须对x和y赋值,否则会报错。
//
y = x;
//
上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
x
=
1
;
y
=
2
;
}
static
void
reftest(
ref
int
x,
ref
int
y)
{
x
=
1
;
y
=
x;
}
public
static
void
main()
{
//
out test
int
a,b;
//
out使用前,变量可以不赋值
outtest(
out
a,
out
b);
console.writeline(
"
a={0};b={1}
"
,a,b);
int
c
=
11
,d
=
22
;
outtest(
out
c,
out
d);
console.writeline(
"
c={0};d={1}
"
,c,d);
//
ref test
int
m,n;
//
reftest(ref m, ref n);
//
上面这行会出错,ref使用前,变量必须赋值
int
o
=
11
,p
=
22
;
reftest(
ref
o,
ref
p);
console.writeline(
"
o={0};p={1}
"
,o,p);
}
}
相关文章推荐
- C# ref与out关键字的使用与区别
- c#中out和ref的使用级区别
- c#中out和ref的使用区别 [转]
- C#中引用参数ref 、out的使用区别
- C#里面ref和out关键字使用与区别
- C#中Ref和out的使用区别
- C#Trick&Tip: 使用 ref 与 out 传递参数的区别
- c#中out和ref的使用区别
- C#中out和ref的使用区别
- c#中out和ref的使用区别
- 史上最全的CSS hack方式一览 jQuery 图片轮播的代码分离 JQuery中的动画 C#中Trim()、TrimStart()、TrimEnd()的用法 marquee 标签的使用详情 js鼠标事件 js添加遮罩层 页面上通过地址栏传值时出现乱码的两种解决方法 ref和out的区别在c#中 总结
- c#中out和ref的使用区别 [转]
- C#中ref和out的使用与区别
- c# out 和 ref 的区别
- c# 中ref 和out的区别
- C#中out 和ref区别
- ref和out的使用与区别
- C#中关键字ref与out的区别
- ref和out的使用与区别
- [C#基础]ref和out的区别