C#中的值类型和引用类型

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

  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 }

 

posted on 2017-04-19 22:29  pandawuwyj  阅读(331)  评论(0编辑  收藏  举报

导航