国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

如何選擇使用結(jié)構(gòu)或類(lèi)

2019-11-17 02:24:51
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

如何選擇使用結(jié)構(gòu)或類(lèi)

struct是值類(lèi)型,隱式繼承自System.ValueType,struct實(shí)例被分配在堆棧上,由系統(tǒng)內(nèi)存回收;class是引用類(lèi)型,class的實(shí)例被分配在托管堆上,由GC回收。

struct不可以有無(wú)參構(gòu)造函數(shù)(這種說(shuō)法不準(zhǔn)確,ChuckLu 提醒應(yīng)說(shuō)成:不能包含顯式的無(wú)參構(gòu)造函數(shù)。也就是說(shuō),struct有默認(rèn)的無(wú)參構(gòu)造函數(shù),不能顯式聲明),只能有帶參構(gòu)造函數(shù);class當(dāng)然可以有無(wú)參構(gòu)造函數(shù)。

struct和class都可以通過(guò)new關(guān)鍵字創(chuàng)建實(shí)例。

struct不能用abstract修飾,可以在class前面加abstract關(guān)鍵字。

struct作為參數(shù)傳遞時(shí),傳遞的是值,而class傳遞的是引用地址。

來(lái)看一個(gè)struct和class類(lèi)型作為參數(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;

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 蛟河市| 涞水县| 蒙阴县| 霍林郭勒市| 静乐县| 青冈县| 玉树县| 梅河口市| 驻马店市| 饶河县| 若尔盖县| 乐清市| 鸡东县| 三明市| 襄樊市| 台北市| 泊头市| 开原市| 乌兰察布市| 酒泉市| 兴宁市| 宝应县| 民丰县| 山东省| 融水| 南汇区| 德阳市| 连江县| 云南省| 涞水县| 阿克| 永吉县| 江城| 大足县| 凭祥市| 垦利县| 济宁市| 文昌市| 仪陇县| 庄河市| 镇平县|