淺析C#中結(jié)構(gòu)與類的區(qū)別
一、
- 結(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
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)用時修改的只是結(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)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
C#根據(jù)http和ftp圖片地址獲取對應(yīng)圖片
這篇文章主要為大家詳細介紹了C#根據(jù)http和ftp圖片地址獲取對應(yīng)圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
C#判斷字符串中是否包含指定字符串及contains與indexof方法效率問題
這篇文章主要介紹了C#判斷字符串中是否包含指定字符串及contains與indexof方法效率問題 ,文中給大家列舉通過兩種方法來判斷,需要的朋友可以參考下2018-10-10
C#使用CefSharp和網(wǎng)頁進行自動化交互的示例代碼
CefSharp 是一個用 C# 編寫的開源庫,它封裝了 Google Chrome 瀏覽器的 Chromium 內(nèi)核,CefSharp 允許開發(fā)者在其應(yīng)用程序中嵌入瀏覽器功能,從而能夠展示網(wǎng)頁內(nèi)容、執(zhí)行JavaScript代碼,本文給大家介紹了C#使用CefSharp和網(wǎng)頁進行自動化交互,需要的朋友可以參考下2024-07-07

