ref与out一看就懂
2011-05-03 11:04
218 查看
讲解一下ref与out的小知识,形象总结的例子让您运用起来的心应手,新手一看就懂,共同进步。
注:1.使用控制台演示一下非常直观,易懂
2.放法1,2和1,3比较您会分别了解ref,out方法的用途与原理。
3.方法2,3比较您会深刻体会ref与out两种引用传递的根本区别,ref的地址引用传递和out的值传递,ref会为变量开辟一块内存空间,保存该变量的地址,直到程序关闭。
4.方法3,4比较您会了解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最常用的用法,方便实用。
相关文章推荐
- 一看就懂:图解C#中的值类型、引用类型、栈、堆、ref、out
- 一看就懂:图解C#中的值类型、引用类型、栈、堆、ref、out
- 使用 ref 和 out 传递数组
- Ref_Out
- C# 使用 ref 和 out 传递数组
- ref 和out
- ref 关键字out关键字
- C#中ref、out类型参数的区别和params类型参数的用法
- c# 中传值用的 ref 和out 好用哦!!
- c#中ref与out的区别
- 关键字ref和out之间的区别
- C#的参数类型:params、out和ref
- ref和out的用法
- (C#)方法参数关键字:ref、out、params详解
- 第一节 49_ref_out
- C# 关键字ref out 的区别
- ref引用类型,数组型参数,out输出参数
- 关于关键字ref和out
- C#下ref和out关键字使用
- C# 中的 Out 和 Ref 参数