在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通常用於小數據場景