国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#:淺析結構與類的區別

2019-11-14 13:49:57
字體:
來源:轉載
供稿:網友
一、
     結構:值類型,存儲在堆棧中,位于計算機的內存邏輯區域中
     類   :引用類型,存儲在堆中,位于計算機內存的不同邏輯位置
 
二、
     較小的數據使用結構;
     將一個結構值傳遞到方法時,傳遞的是整個數據結構;
     傳遞一個類,實際上是將引用傳遞到對象,即只有內存地址;
     對結構修改,改變的是結構的副本,這是值類型工作方式的定義:傳遞值的副本;
     傳遞一個引用到類本身意味著在類中修改值,實際上改變的是原始對象;
 
三、代碼栗子
  1.新建 PointClass.cs
 1 namespace StructAndClass 2 { 3     internal class PointClass 4     { 5         public PointClass(int x, int y) 6         { 7             X = x; 8             Y = y; 9         }10 11         public int X { get; set; }12 13         public int Y { get; set; }14     }15 }

 

  2.新建 PointStruct.cs

 1 namespace StructAndClass 2 { 3     internal struct PointStruct 4     { 5         public int X { get; set; } 6  7         public int Y { get; set; } 8  9         public PointStruct(int x, int y)10         {11             X = x;12             Y = y;13         }14     }15 }

 

  3.PRogram.cs

 1 using System; 2  3 namespace StructAndClass 4 { 5     internal class Program 6     { 7         private static void Main(string[] args) 8         { 9             Console.WriteLine("PointStruct =====");10             var pStruct = new PointStruct(10, 10);11             Console.WriteLine("初始值:x={0},y={1}", pStruct.X, pStruct.Y);12             ModifyPointStruct(pStruct);13             Console.WriteLine("調用 ModifyPointStruct() 后的值:x={0},y={1}", pStruct.X, pStruct.Y);14             Console.WriteLine();15 16             Console.WriteLine("PointClass =====");17             var pClass = new PointClass(10, 10);18             Console.WriteLine("初始值:x={0},y={1}", pClass.X, pClass.Y);19             ModifyPointClass(pClass);20             Console.WriteLine("調用 ModifyPointClass() 后的值:x={0},y={1}", pClass.X, pClass.Y);21             Console.Read();22         }23 24         private static void ModifyPointStruct(PointStruct point)25         {26             Console.WriteLine("調用方法:ModifyPointStruct");27             point.X = 20;28             point.Y = 20;29             Console.WriteLine("修改成的值:x={0}, y={1}", point.X, point.Y);30         }31 32         private static void ModifyPointClass(PointClass point)33         {34             Console.WriteLine("調用方法:ModifyPointClass");35             point.X = 20;36             point.Y = 20;37             Console.WriteLine("修改成的值:x={0}, y={1}", point.X, point.Y);38         }39     }40 }

 

  4.結果:

【解析】

  ModifyPointStruct(PointStruct point) 調用時修改的只是結構副本,所以原來的結構并沒有發生變化;  
  ModifyPointClass(PointClass point) 調用時所修改的對象是原對象,因為參數傳遞過來的是一個引用地址,這地址指向原對象

四、總結

  結構是值類型并在堆棧中傳遞,每次使用方法進行修改的都只是結構副本;

      至于類,傳遞的是內存地址的引用,修改的就是初始值

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 濮阳市| 大荔县| 商河县| 靖西县| 东宁县| 赤壁市| 互助| 柘城县| 襄城县| 汾西县| 龙口市| 昌吉市| 凭祥市| 潍坊市| 金湖县| 白朗县| 涟源市| 内黄县| 盘锦市| 清涧县| 万全县| 琼海市| 历史| 武乡县| 长治市| 丹阳市| 台安县| 普安县| 周宁县| 文昌市| 泰安市| 德昌县| 永登县| 西平县| 呼和浩特市| 石楼县| 巨野县| 双牌县| 巨野县| 吴江市| 鄂伦春自治旗|