.NET:默认是按值传递的

小测试

代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Linq.Expressions;
 7 using System.Threading;
 8 
 9 namespace CSharpStudy
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             {
16                 var t1 = new TestClass();
17                 var t2 = TestMethod1(t1);
18 
19                 Console.WriteLine(t1.Value);
20                 Console.WriteLine(t2);
21             }
22             {
23                 var t1 = new TestClass();
24                 var t2 = TestMethod2(ref t1);
25 
26                 Console.WriteLine(t1);
27                 Console.WriteLine(t2);
28             }
29         }
30 
31         private static TestClass TestMethod1(TestClass test)
32         {
33             test.Value = 10;
34             test = null;
35             return test;
36         }
37 
38         private static TestClass TestMethod2(ref TestClass test)
39         {
40             test.Value = 10;
41             test = null;
42             return test;
43         }
44     }
45 
46     internal class TestClass
47     {
48         public int Value { get; set; }
49     }
50 }

输出

如果输出结果你不意外,也能理解到底发生了什么,那么就不用看这篇文章了。

默认是按值传递的

var a = new TestClass(); 中 a 叫“reference”,等号右侧叫“instance”,作为局部变量的 reference 分配在栈中,作为成员的 reference 内联存储在堆中,instance 始终分配在堆中,reference 指向了 instance,可以理解为存储了 instance 的地址。

var a = new TestStruct(); 中 a 叫“value”,右侧返回的值就分配在 a 中,作为局部变量的 value 分配在栈中,作为成员的 value 内联存储在堆中。

.NET 默认是按值进行传递的(参数传递、变量之间的赋值),var a = b; 中如果 b 是引用类型,栈中就有两个引用,一个对象,两个引用共同指向同一个对象。如果 b 是值类型,栈中就有两个值,彼此独立。

 

posted on 2014-01-29 16:23  幸福框架  阅读(524)  评论(0编辑  收藏  举报

导航

我要啦免费统计