参数类表中的out ref
2015-09-05 09:36
423 查看
class text{
public static void Main(String [] args){
int m =100;
int n =200;
Sub(out m , n);
Console.WriteLine(m + "\n"+n);
Add(ref m , ref n);
Console.WriteLine(m + "\n"+n);
Console.ReadKey();
}
private static void Sub(out int a,int b){
a =10;
b = 20;
if(a<b){
a =1000;
b =0;
}
int result = a-b;
Console.WriteLine(result);
}
private static void Add(ref int a , ref int b){
a=600;
b=600;
int result = a+b;
Console.WriteLine(result);
}
}
1000 1000 200 1200 600 600
输出参数和引用参数的区别:
从CLR的角度来看,关键字out和关键字ref是等效的,这就是说,无论使用哪个关键字都会产生相同的元数据和IL代码。但是,C#编译器将两个关键字区别对待,在C#中,这俩个关键字的区别在于哪个方法负责初始化引用对象。
1.如果方法参数标记为out,那么调用者不希望在调用方法之前初始化对象,被调用的方法不能读取对象的值,而且被调用的方法必须返回之前为对象赋值。
2.如果方法的参数标记为ref,那么调用者必须在调用方法之前初始化参数的值,被调用方法可以读取或为参数赋值。
static void Main(string[] args)
{
int i; //out可以不赋初值
test(out i);
Console.WriteLine(i);
int j = 0;
test2(ref j);
Console.WriteLine(j);
Console.ReadKey();
}
static void test(out int i) {
i = 123;
}
static void test2(ref int j) {
j = 2;
}
public static void Main(String [] args){
int m =100;
int n =200;
Sub(out m , n);
Console.WriteLine(m + "\n"+n);
Add(ref m , ref n);
Console.WriteLine(m + "\n"+n);
Console.ReadKey();
}
private static void Sub(out int a,int b){
a =10;
b = 20;
if(a<b){
a =1000;
b =0;
}
int result = a-b;
Console.WriteLine(result);
}
private static void Add(ref int a , ref int b){
a=600;
b=600;
int result = a+b;
Console.WriteLine(result);
}
}
1000 1000 200 1200 600 600
输出参数和引用参数的区别:
从CLR的角度来看,关键字out和关键字ref是等效的,这就是说,无论使用哪个关键字都会产生相同的元数据和IL代码。但是,C#编译器将两个关键字区别对待,在C#中,这俩个关键字的区别在于哪个方法负责初始化引用对象。
1.如果方法参数标记为out,那么调用者不希望在调用方法之前初始化对象,被调用的方法不能读取对象的值,而且被调用的方法必须返回之前为对象赋值。
2.如果方法的参数标记为ref,那么调用者必须在调用方法之前初始化参数的值,被调用方法可以读取或为参数赋值。
static void Main(string[] args)
{
int i; //out可以不赋初值
test(out i);
Console.WriteLine(i);
int j = 0;
test2(ref j);
Console.WriteLine(j);
Console.ReadKey();
}
static void test(out int i) {
i = 123;
}
static void test2(ref int j) {
j = 2;
}
相关文章推荐
- 大数据之sqoop
- 【uva 11021】Tribbles
- 列表样式切换
- error: file 'boot/grub/i386-pc/normal.mod' not found
- Coursera机器学习课程笔记(3) Logistic Regression
- delphi 线程实战用法
- 噪声振动模拟仿真ESI VA One 2015.0
- js制作带有遮罩弹出层实现登录注册表单特效代码分享
- Java中的定时调度
- Linux设置固定IP
- ARC的应用
- ANDROID开发之SQLite详解
- LeetCode || Lowest Common Ancestor of a Binary Search Tree
- 开关智能管理工具NI Switch Executive 15.10
- Android Studio如何快速生成get,set,tostring,构造函数
- OpenCv 使用morphologyEx 进行更多的变化
- uvalive4015 (树上背包)
- nginx+tomcat负载均衡实现session共享
- python+opencv实现基于图片序列的三维重建
- hdu4417