C#中ref和out的使用小结
来源:互联网 发布:个人域名备案需要多久 编辑:程序博客网 时间:2024/05/16 16:02
ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。
使用ref前必须对变量赋值,out不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
区别可以参看下面的代码:
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不用。
out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。
区别可以参看下面的代码:
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#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结(ZZ)
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- 【转】为人处世28条及注解
- OpenIPMP中的ISMACryp
- VS2005调试问题解决方案集锦--引用
- 忘掉web2.0,抓住web3.0
- OMA DRM 1.0 – OMA Download 框架
- C#中ref和out的使用小结
- 调查:主流手机操作系统对OMA DRM的支持
- OMA DRM V1.0学习笔记
- Linux环境下USB的原理、驱动和配置
- OpenIPMP中Cryptopp库的重编译
- 《游戏编程》第一部 基础篇
- OpenIPMP组件列表
- OpenIPMP中的几个关键概念
- ASP.NET定义主题和外观