您的位置:首页 > 职场人生

ref与out一看就懂

2011-05-03 11:04 218 查看
讲解一下ref与out的小知识,形象总结的例子让您运用起来的心应手,新手一看就懂,共同进步。

class Program
{
static void Main(string[] args)
{

//两次调用show1方法,比较两次的a值
int a = 0;
show1(a);
Console.WriteLine(a);
show1(a);
Console.WriteLine(a + "\n");

//两次调用show1的ref重载方法,比较两次的a值
int b = 0;
show1(b);
Console.WriteLine(b);
show1(b);
Console.WriteLine(b + "\n");

//调用show2方法(注:show1方法已经定义了ref的重载方法,则不能定义out的重载方法)
int c = 0;
show2(out c);
Console.WriteLine(c);

//调用show3方法返回两个不同类型的值
int d = 0;
string e = show3(out d);
Console.WriteLine(d);
Console.WriteLine(e);

}
///方法一
protected static void show1(int i1)
{
i1++;
}
///方法二
protected static void show1(ref int i1)
{
i1++;
}
///方法三
protected static void show2(out int i1)
{
i1 = 5;
}
///方法四
protected static string show3(out int i1)
{
i1 = 5;
return "注意我是怎么返回了两个不同类型值呢";
}


注:1.使用控制台演示一下非常直观,易懂

2.放法1,2和1,3比较您会分别了解ref,out方法的用途与原理。

3.方法2,3比较您会深刻体会ref与out两种引用传递的根本区别,ref的地址引用传递和out的值传递,ref会为变量开辟一块内存空间,保存该变量的地址,直到程序关闭。

4.方法3,4比较您会了解out最常用的用法,方便实用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息