关于引用类型和值类型作为参数传递的随笔

  作为博客园的新手,首次发帖,如有不对的地方,请拍砖!

  先上代码:

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         IList<int> list = null;
 6         SetValue(list);
 7         foreach (int item in list)
 8             Console.WriteLine(item);
 9 
10         Console.ReadKey();
11     }
12 
13     static void SetValue(IList<int> list)
14     {
15         list = SetValue();
16     }
17 
18     static IList<int> SetValue()
19     {
20         IList<int> list = new List<int>();
21         for (int i = 0; i < 10; i++)
22             list.Add(i);
23         return list;
24     }
25 }
View Code

  众所周知,值类型是存储在占内存中的,引用类型是存储在堆内存中。学习过 C 语言的同学都知道,引用类型中存储的是引用类型变量在堆中存放的起始地址。当引用类型 list 作为参数传入一个方法,且没有 out 或 ref 修饰时,list 是作为值类型传入了方法中。

  当 list 作为参数进行传递时,传递的是 list 在栈内存中的拷贝,所以在上面代码中拿到的 list 为 null。

  当参数有 out 或 ref 修饰时,传递的是该变量自己的地址。通过该地址可以直接访问栈内存,如果是值类型,则直接读取到了该变量的值;如果是引用类型,则通过在栈内存中存储的堆内存地址访问堆中的变量值。

posted @ 2016-04-22 13:28  劳资  阅读(145)  评论(0)    收藏  举报