一、
- 結(jié)構(gòu):值類型,存儲在堆棧中,位于計算機的內(nèi)存邏輯區(qū)域中
- 類 :引用類型,存儲在堆中,位于計算機內(nèi)存的不同邏輯位置
二、
- 較小的數(shù)據(jù)使用結(jié)構(gòu);
- 將一個結(jié)構(gòu)值傳遞到方法時,傳遞的是整個數(shù)據(jù)結(jié)構(gòu);
- 傳遞一個類,實際上是將引用傳遞到對象,即只有內(nèi)存地址;
- 對結(jié)構(gòu)修改,改變的是結(jié)構(gòu)的副本,這是值類型工作方式的定義:傳遞值的副本;
- 傳遞一個引用到類本身意味著在類中修改值,實際上改變的是原始對象;
三、代碼例子
1.新建 PointClass.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
|
namespace StructAndClass { internal class PointClass { public PointClass( int x, int y) { X = x; Y = y; } public int X { get ; set ; } public int Y { get ; set ; } } } |
2.新建 PointStruct.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
|
namespace StructAndClass { internal struct PointStruct { public int X { get ; set ; } public int Y { get ; set ; } public PointStruct( int x, int y) { X = x; Y = y; } } } |
3.Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
using System; namespace StructAndClass { internal class Program { private static void Main( string [] args) { Console.WriteLine( "PointStruct =====" ); var pStruct = new PointStruct(10, 10); Console.WriteLine( "初始值:x={0},y={1}" , pStruct.X, pStruct.Y); ModifyPointStruct(pStruct); Console.WriteLine( "調(diào)用 ModifyPointStruct() 后的值:x={0},y={1}" , pStruct.X, pStruct.Y); Console.WriteLine(); Console.WriteLine( "PointClass =====" ); var pClass = new PointClass(10, 10); Console.WriteLine( "初始值:x={0},y={1}" , pClass.X, pClass.Y); ModifyPointClass(pClass); Console.WriteLine( "調(diào)用 ModifyPointClass() 后的值:x={0},y={1}" , pClass.X, pClass.Y); Console.Read(); } private static void ModifyPointStruct(PointStruct point) { Console.WriteLine( "調(diào)用方法:ModifyPointStruct" ); point.X = 20; point.Y = 20; Console.WriteLine( "修改成的值:x={0}, y={1}" , point.X, point.Y); } private static void ModifyPointClass(PointClass point) { Console.WriteLine( "調(diào)用方法:ModifyPointClass" ); point.X = 20; point.Y = 20; Console.WriteLine( "修改成的值:x={0}, y={1}" , point.X, point.Y); } } } |
4.結(jié)果:
【解析】
ModifyPointStruct(PointStruct point) 調(diào)用時修改的只是結(jié)構(gòu)副本,所以原來的結(jié)構(gòu)并沒有發(fā)生變化;
ModifyPointClass(PointClass point) 調(diào)用時所修改的對象是原對象,因為參數(shù)傳遞過來的是一個引用地址,這地址指向原對象
四、總結(jié)
結(jié)構(gòu)是值類型并在堆棧中傳遞,每次使用方法進行修改的都只是結(jié)構(gòu)副本;
至于類,傳遞的是內(nèi)存地址的引用,修改的就是初始值
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/liqingwen/p/4929057.html