一、
- 結構:值類型,存儲在堆棧中,位于計算機的內存邏輯區域中
- 類 :引用類型,存儲在堆中,位于計算機內存的不同邏輯位置
二、
- 較小的數據使用結構;
- 將一個結構值傳遞到方法時,傳遞的是整個數據結構;
- 傳遞一個類,實際上是將引用傳遞到對象,即只有內存地址;
- 對結構修改,改變的是結構的副本,這是值類型工作方式的定義:傳遞值的副本;
- 傳遞一個引用到類本身意味著在類中修改值,實際上改變的是原始對象;
三、代碼例子
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( "調用 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( "調用 ModifyPointClass() 后的值:x={0},y={1}" , pClass.X, pClass.Y); Console.Read(); } private static void ModifyPointStruct(PointStruct point) { Console.WriteLine( "調用方法: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( "調用方法:ModifyPointClass" ); point.X = 20; point.Y = 20; Console.WriteLine( "修改成的值:x={0}, y={1}" , point.X, point.Y); } } } |
4.結果:
【解析】
ModifyPointStruct(PointStruct point) 調用時修改的只是結構副本,所以原來的結構并沒有發生變化;
ModifyPointClass(PointClass point) 調用時所修改的對象是原對象,因為參數傳遞過來的是一個引用地址,這地址指向原對象
四、總結
結構是值類型并在堆棧中傳遞,每次使用方法進行修改的都只是結構副本;
至于類,傳遞的是內存地址的引用,修改的就是初始值
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/liqingwen/p/4929057.html