struct是值類型,隱式繼承自System.ValueType,struct實例被分配在堆棧上,由系統(tǒng)內(nèi)存回收;class是引用類型,class的實例被分配在托管堆上,由GC回收。
struct不可以有無參構(gòu)造函數(shù)(這種說法不準(zhǔn)確,ChuckLu 提醒應(yīng)說成:不能包含顯式的無參構(gòu)造函數(shù)。也就是說,struct有默認(rèn)的無參構(gòu)造函數(shù),不能顯式聲明),只能有帶參構(gòu)造函數(shù);class當(dāng)然可以有無參構(gòu)造函數(shù)。
struct和class都可以通過new關(guān)鍵字創(chuàng)建實例。
struct不能用abstract修飾,可以在class前面加abstract關(guān)鍵字。
struct作為參數(shù)傳遞時,傳遞的是值,而class傳遞的是引用地址。
來看一個struct和class類型作為參數(shù)傳遞的例子。
class PRogram{static void Main(string[] args){PointStruct structPoint = new PointStruct();structPoint.x = 10;structPoint.y = 10;Console.WriteLine("struct的初始值是:x={0},y={1}",structPoint.x, structPoint.y);ChangeStructPoint(structPoint);Console.WriteLine("struct的初始值改變后是:x={0},y={1}", structPoint.x, structPoint.y);Console.WriteLine();PointClass pointClass = new PointClass(10, 10);Console.WriteLine("class的初始值是:x={0},y={1}", pointClass.x, pointClass.y);ChangeClassPoint(pointClass);Console.WriteLine("class的初始值改變后是:x={0},y={1}", pointClass.x, pointClass.y);Console.ReadKey();}static void ChangeStructPoint(PointStruct pointStruct){pointStruct.x = 20;pointStruct.y = 20;Console.WriteLine("正在改變struct的值是:x={0},y={1}", pointStruct.x, pointStruct.y);}static void ChangeClassPoint(PointClass pointClass){pointClass.x = 20;pointClass.y = 20;Console.WriteLine("正在改變class的值是:x={0},y={1}", pointClass.x, pointClass.y);}}public struct PointStruct{public int x;
新聞熱點
疑難解答