首页 > 其他 > 详细

值类型与引用类型

时间:2018-11-06 17:21:18      阅读:173      评论:0      收藏:0      [点我收藏+]

先上代码

 1 class TestClass
 2 {
 3     public int val;
 4 }
 5 struct TestStruct
 6 {
 7     public int val;
 8 }
 9 
10 class Program
11 {
12     static void Main(string[] args)
13     {
14         TestClass testClass1 = new TestClass();
15         TestClass testClass2 = testClass1;
16         testClass1.val = 10;
17         testClass2.val = 20;
18 
19         TestStruct testStruct1 = new TestStruct();
20         TestStruct testStruct2 = testStruct1;
21         testStruct1.val = 30;
22         testStruct2.val = 40;
23 
24         WriteLine($"testClass1.val = {testClass1.val}");
25         WriteLine($"testClass2.val = {testClass2.val}");
26         WriteLine($"testStruct1.val = {testStruct1.val}");
27         WriteLine($"testStruct2.val = {testStruct2.val}");
28 
29         ReadKey();
30 
31     }
32 }

运行结果为

技术分享图片

出现这种情况是因为结构为值类型,类为引用类型

书里给出的解释是把对象赋给变量时,实际是把带有一个指针的变量赋给了该指针所指向的对象。

画一个我理解的图

技术分享图片

结构是值类型,并不包含指针,所以,只是单纯的把第一个结构的所有信息复制到第二个结构中

 

值类型与引用类型

原文:https://www.cnblogs.com/xt112233/p/9916310.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!