struct class 區別

來源:互聯網
上載者:User

記得以前學C語言老師就講過struct,那個時候struct主要是用在鏈表的處理中。後來自己學了C++,才開始接觸class,class就不用我介紹了吧。.NET裡對struct和class這兩個關鍵字都有支援,剛開始學C#的時候就以為C#保留struct是為了與以前的語言相容一下,struct只是class的另一種表現形式罷了。在看了《Applied Microsoft .Net Framework Programming》後,才發現struct與class間的關係並不只是那麼簡單。

class是參考型別,特點:1、記憶體必須從託管堆分配;2、每個在託管堆中分配的對象有一些與之關聯的附加成員必須初始化;3、從託管堆中分配的對象可能會導致垃圾收集。我對參考型別的理解就是個指標。

Struct是實值型別,分配線上程的堆棧上,不包含指向執行個體的指標。就像int、double、char這些實值型別一樣,也就是他們本身儲存了值。

舉個非常簡單的例子就能說明問題(這個例子來自那本書):

 1using System;
 2
 3namespace struct與class
 4{
 5    //參考型別
 6    class SomeRef {public int x;}
 7    //實值型別
 8    struct SomeVal {public int x;}
 9
10    class Class1
11    {
12        [STAThread]
13        static void Main(string[] args)
14        {
15            SomeRef r1=new SomeRef();
16            SomeVal v1=new SomeVal();
17            r1.x=5;
18            v1.x=5;
19            Console.WriteLine("Before Evaluation:");
20            Console.WriteLine("r1.x="+r1.x);
21            Console.WriteLine("v1.x="+v1.x);
22
23            SomeRef r2=r1;
24            SomeVal v2=v1;
25            r1.x=8;
26            v2.x=9;
27
28            Console.WriteLine("After Evaluation:");
29            Console.WriteLine("r1.x="+r1.x+";r2.x="+r2.x);
30            Console.WriteLine("v1.x="+v1.x+";v2.x="+v2.x);
31        }
32    }
33}
34

結果:

Before Evaluation:

r1.x=5

v1.x=5

 

After Evaluation:

r1.x=8;r2.x=8

v1.x=5;v2.x=9

 

很明顯,對v2的修改未影響到v1,對r1的修改影響到了r2。

畫個圖說明一下它們的記憶體配置:

 

那保留struct還有什麼用呢,既然都用class。說句老實話,我也覺得沒什麼用,雖然書上說線上程棧上更快,但畢竟沒有GC照顧你,object的深拷貝也比較好實現。權當是C#的一個知識點,記住就行了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.