C#------值类型与引用类型

定义:

  1. 值类型直接存储其值,存储在堆栈中;
  2. 引用类型存储对值的引用,存储在托管堆中。

例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         class Vector
12         {
13             public int value;
14         }
15         static void Main(string[] args)
16         {
17             Vector x, y;
18             x = new Vector();
19             x.value = 30;
20             y = x;
21             Console.WriteLine(y.value);
22             y.value = 10;
23             Console.WriteLine(x.value);
24             Console.ReadKey();
25         }
26     }
27 }

该例程中只创建了一个对象,x,y都是只向包含该内存的位置,因此他们都是引用类型变量,什么这两个变量只是保留了一个引用。由此结论,x,y引用的是同一个对象,对x的修改会影响y,反之亦然。

例程运行结果:

30

10

原文地址:https://www.cnblogs.com/lumao1122-Milolu/p/11629914.html