淺析C#中結(jié)構(gòu)與類的區(qū)別
一、
- 結(jié)構(gòu):值類型,存儲(chǔ)在堆棧中,位于計(jì)算機(jī)的內(nèi)存邏輯區(qū)域中
- 類 :引用類型,存儲(chǔ)在堆中,位于計(jì)算機(jī)內(nèi)存的不同邏輯位置
二、
- 較小的數(shù)據(jù)使用結(jié)構(gòu);
- 將一個(gè)結(jié)構(gòu)值傳遞到方法時(shí),傳遞的是整個(gè)數(shù)據(jù)結(jié)構(gòu);
- 傳遞一個(gè)類,實(shí)際上是將引用傳遞到對(duì)象,即只有內(nèi)存地址;
- 對(duì)結(jié)構(gòu)修改,改變的是結(jié)構(gòu)的副本,這是值類型工作方式的定義:傳遞值的副本;
- 傳遞一個(gè)引用到類本身意味著在類中修改值,實(shí)際上改變的是原始對(duì)象;
三、代碼例子
1.新建 PointClass.cs
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
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
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)用時(shí)修改的只是結(jié)構(gòu)副本,所以原來的結(jié)構(gòu)并沒有發(fā)生變化;
ModifyPointClass(PointClass point) 調(diào)用時(shí)所修改的對(duì)象是原對(duì)象,因?yàn)閰?shù)傳遞過來的是一個(gè)引用地址,這地址指向原對(duì)象
四、總結(jié)
結(jié)構(gòu)是值類型并在堆棧中傳遞,每次使用方法進(jìn)行修改的都只是結(jié)構(gòu)副本;
至于類,傳遞的是內(nèi)存地址的引用,修改的就是初始值
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
C#根據(jù)http和ftp圖片地址獲取對(duì)應(yīng)圖片
這篇文章主要為大家詳細(xì)介紹了C#根據(jù)http和ftp圖片地址獲取對(duì)應(yīng)圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06c# 應(yīng)用事務(wù)的簡(jiǎn)單實(shí)例
這篇文章介紹了c# 應(yīng)用事務(wù)的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-09-09C#判斷字符串中是否包含指定字符串及contains與indexof方法效率問題
這篇文章主要介紹了C#判斷字符串中是否包含指定字符串及contains與indexof方法效率問題 ,文中給大家列舉通過兩種方法來判斷,需要的朋友可以參考下2018-10-10C#使用CefSharp和網(wǎng)頁(yè)進(jìn)行自動(dòng)化交互的示例代碼
CefSharp 是一個(gè)用 C# 編寫的開源庫(kù),它封裝了 Google Chrome 瀏覽器的 Chromium 內(nèi)核,CefSharp 允許開發(fā)者在其應(yīng)用程序中嵌入瀏覽器功能,從而能夠展示網(wǎng)頁(yè)內(nèi)容、執(zhí)行JavaScript代碼,本文給大家介紹了C#使用CefSharp和網(wǎng)頁(yè)進(jìn)行自動(dòng)化交互,需要的朋友可以參考下2024-07-07