引用类型:总是从托管堆分配

  class, interface, delegate

  System.Object, System.String, List, Decoder等

值类型:一般分配在线程栈上(例外情况:数组中的元素、引用类型中的值类型字段、迭代器块中的局部变量、闭包情况下lambda中的局部变量)

  struct

  System.Int32, System.Float, System.Boolean, System.Enum

 

主要看一下class与struct:

 1 namespace RefValTest
 2 {
 3     class TestRef
 4     {
 5         public int a;
 6         public int b;
 7 
 8         public TestRef(int a, int b)
 9         {
10             this.a = a;
11             this.b = b;
12         }
13     }
14 
15     struct TestVal
16     {
17         public int a;
18         public int b;
19 
20         public TestVal(int a, int b)
21         {
22             this.a = a;
23             this.b = b;
24         }
25     }
26 
27     class Program
28     {
29         static void Main(string[] args)
30         {
31             TestRef tr = new TestRef(1, 2);
32             TestRef tr2 = tr;
33             tr2.a = 3;
34             System.Console.WriteLine(tr.a); // 3
35 
36             TestVal tv = new TestVal(1, 2);
37             TestVal tv2 = tv;
38             tv2.a = 3;
39             System.Console.WriteLine(tv.a); // 1
40 
41             System.Console.ReadLine();
42         }
43     }
44 }

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!