您的位置:首页 > 其它

参数类表中的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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: