小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

C#中Struct和Class的區(qū)別

 怡紅公子0526 2021-04-06

在C#中,struct和class都是用戶定義的數(shù)據(jù)類型,struct和class有許多不同之處,但主要的區(qū)別是:

Class是引用類型,它保存在堆上并且能夠被垃圾回收;然而stuct是值類型,它保存在棧上或者內(nèi)嵌在它的包含類型之中。因此,從總體上來說struct比class節(jié)省內(nèi)存。

 

下圖是Class和Struct的14個不同之處:

 

詳解Class與Stuct的不同之處

1.struct用"struct"關(guān)鍵字來聲明,而class用"class"關(guān)鍵字聲明(好像是廢話)

2.由于struct是值類型,所以struct的變量直接包含了數(shù)據(jù)本身;而class是引用類型,所以class的變量只是包含了對數(shù)據(jù)的引用(其實就是一個指針)

3.class類型的變量,其內(nèi)存分配在堆上并且能夠被垃圾回收,然而stuct類型的變量的內(nèi)存分配在棧上或者內(nèi)嵌在它的包含類型中

4.class的對象需要通過"new"關(guān)鍵字來創(chuàng)建,而創(chuàng)建struct的對象時,可以用也可以不用"new"關(guān)鍵字。如何實例化struct時沒有用"new", 則用戶不允許訪問其方法、事件和屬性。

5.每個struct變量都包含它的數(shù)據(jù)的一個copy(ref和out參數(shù)是個例外),所以對一個變量的修改不會影響別的變量;然則對于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節(jié)省內(nèi)存

7.struct不能有無參數(shù)構(gòu)造函數(shù),可以有有參數(shù)的或者static構(gòu)造函數(shù);而class默認(rèn)會有一個無參數(shù)的構(gòu)造函數(shù)

8.struct不能有析構(gòu)函數(shù),而class可以有

9.struct不能從另一個struct或者class繼承而來,也不能作為基類使用;而class可以繼承自其他class,也可以作為基類使用??傊?,stuct不支持繼承,class支持繼承。

10.struct的成員不能聲明成abstract, virtual或者protected, 而class可以

11.class的實例稱為對象(object), struct的實例稱為結(jié)構(gòu)變量

12.如果未指定訪問指示符,對class而言,其成員默認(rèn)是private,而對struct而言,默認(rèn)是public

13.class通常用于復(fù)雜的數(shù)據(jù)結(jié)構(gòu)的場景,而struct通常用于小數(shù)據(jù)場景

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多