在C#中,struct和class都是用戶定義的資料型別,struct和class有許多不同之處,但主要的區別是:
Class是參考型別,它保存在堆上并且能夠被垃圾回收;然而stuct是值型別,它保存在堆疊上或者內嵌在它的包含型別之中,因此,從總體上來說struct比class節省記憶體,
下圖是Class和Struct的14個不同之處:

詳解Class與Stuct的不同之處
1.struct用"struct"關鍵字來宣告,而class用"class"關鍵字宣告(好像是廢話)
2.由于struct是值型別,所以struct的變數直接包含了資料本身;而class是參考型別,所以class的變數只是包含了對資料的參考(其實就是一個指標)
3.class型別的變數,其記憶體分配在堆上并且能夠被垃圾回收,然而stuct型別的變數的記憶體分配在堆疊上或者內嵌在它的包含型別中
4.class的物件需要通過"new"關鍵字來創建,而創建struct的物件時,可以用也可以不用"new"關鍵字,如何實體化struct時沒有用"new", 則用戶不允許訪問其方法、事件和屬性,
5.每個struct變數都包含它的資料的一個copy(ref和out引數是個例外),所以對一個變數的修改不會影響別的變數;然則對于class來說,所有變數(通過賦值宣告的變數)都指向同一物件,對一個變數的修改會影響別的變數,
通過正面的例子可以加深理解
using System; namespace structAndClass { //creating structure public struct Demo { public int x, y; //parameterized constructor public Demo(int x, int y) { this.x = x; this.y = y; } } public class StructDemo { public static void Main(string[] args) { Demo a = new Demo(50, 50); Demo b = a; a.x = 100; Console.WriteLine("Value of a.x = "+a.x); Console.WriteLine("Value of b.x = "+b.x); } } }
輸出
using System; namespace structAndClass { public class Demo { public int x, y; public Demo(int x, int y) { this.x = x; this.y = y; } } public class StructDemo { public static void Main(string[] args) { Demo a = new Demo(50, 50); Demo b = a; a.x = 100; Console.WriteLine("Value of a.x = "+a.x); Console.WriteLine("Value of b.x = "+b.x); } } }
輸出
6.struct比class節省記憶體
7.struct不能有無引數建構式,可以有有引數的或者static建構式;而class默認會有一個無引數的建構式
8.struct不能有解構式,而class可以有
9.struct不能從另一個struct或者class繼承而來,也不能作為基類使用;而class可以繼承自其他class,也可以作為基類使用,總之,stuct不支持繼承,class支持繼承,
10.struct的成員不能宣告成abstract, virtual或者protected, 而class可以
11.class的實體稱為物件(object), struct的實體稱為結構變數
12.如果未指定訪問指示符,對class而言,其成員默認是private,而對struct而言,默認是public
13.class通常用于復雜的資料結構的場景,而struct通常用于小資料場景
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/56711.html
標籤:C#
