C#中Struct與Class的區別

來源:互聯網
上載者:User

標籤:io   ar   使用   sp   for   on   資料   div   bs   

1,class 是參考型別,structs是實值型別

既然class是參考型別,class可以設為null。但是我們不能將struct設為null,因為它是實值型別。

struct AStruct

{

   int aField;

}

 

class AClass

{

   int aField;

}

 

class MainClass

{

 public static void Main()

 {

    AClass b = null; // No error.

    AStruct s = null; // Error [ Cannot convert null to ‘AStruct‘because it is a value type ].

 }

}

2,當你執行個體化一個class,它將建立在堆上。而你執行個體化一個struct,它將建立在棧上

3,你使用的是一個對class執行個體的引用。而你使用的不是對一個struct的引用。(而是直接使用它們)

4,當我們將class作為參數傳給一個方法,我們傳遞的是一個引用。struct傳遞的是值而非引用。

5,structs 不可以有初始化器,class可以有初始化器。

class MyClass

{   

 int myVar =10; // no syntax error.   

 public void MyFun( )

 { // statements }

}

 

struct MyStruct

{   

 int myVar = 10; // syntax error.   

 public void MyFun( ) 

 {// statements }

}

 

6,Classes 可以有明顯的無參數構造器,但是Struct不可以

class MyClass

{  

 int myVar = 10;

 public MyClass( ) // no syntax error. 

 {   

// statements

  }

}

struct MyStruct

 int myVar;

 public MyStruct( ) // syntax error.

   {      

               // statements 

   }

}

 

7,類使用前必須new關鍵字執行個體化,Struct不需要

MyClass aClassObj;     // MyClass aClassObj=new MyClass(); is the correct format.aClassObj.

myVar=100;//NullReferenceException(because aClassObj does not contain a reference to an object of type myClass).

 

MyStruct aStructObj;

aStructObj.myVar=100; // no exception.

 

8,class支援繼承和多態,Struct不支援. 注意:但是Struct 可以和類一樣實現介面

9,既然Struct不支援繼承,其成員不能以protected 或Protected Internal 修飾

10,Class的構造器不需要初始化全部欄位,Struct的構造器必須初始化所有欄位

 

class MyClass    //No error( No matter whether the Field ‘ MyClass.myString ‘ is initialized or not ).

{

 int myInt; 

 string myString;  

 public MyClass( int aInt )

 {    myInt = aInt;    }

}

struct MyStruct    // Error ( Field ‘ MyStruct.myString ‘ must be fully assigned before it leaves the constructor ).

{

 int myInt; 

 string myString;

 public MyStruct( int aInt )

   {   

    myInt = aInt; 

   }

}

11,Class可以定義析構器,但是Struct不可以

12,Class比較適合大的和複雜的資料,Struct適用於作為經常使用的一些資料群組合成的新類型。

 

適用場合:Struct有效能優勢,Class有物件導向的擴充優勢。

用於底層資料存放區的類型設計為Struct類型,將用於定義應用程式行為的類型設計為Class。如果對類型將來的應用情況不能確定,應該使用Class。

 

C#中Struct與Class的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.