C#結構

來源:互聯網
上載者:User

標籤:style   blog   color   io   使用   ar   資料   div   sp   

結構的聲明可以使用類似類的聲明,譬如

A a=new A();

//{

  因為結構會隱式聲明一個迷人的建構函式,而且與類不同的是無論是否有自訂建構函式,都存在預設建構函式;但是使用者就會無法自訂無參數的建構函式(避免重複)

  不允許使用解構函式;

  可以使用執行個體建構函式和靜態建構函式;

//}

 

還可以使用直接聲明,譬如

A a;

此時要注意無法在賦值之前調用結構的成員,同時無法在所有資料成員被賦值之前調用函數;

 

結構的成員不能在結構內聲明的時候進行初始化,即

1 struct Point2     {3         public int X=1;4         public int Y=1;5     }

會報錯;

 

結構不能初始化為null,因為他是實值型別,不是類類型;

 

對結構體賦值的時候,兩個結構體s1,s2會相同,但是注意只是進行了值拷貝,但是類是進行的引用拷貝,即結構體中更改s1不會影響s2,但是在類中會影響,例如:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6  7 namespace Struct 8 { 9     class CS10     {11         public int x;12         public int y;13     }14     struct S15     {16         public int x;17         public int y;18     }19     class Program20     {21         static void Main(string[] args)22         {23             CS cs1 = new CS();24             CS cs2 = new CS();25 26             S s1 = new S();27             S s2 = new S();28 29             cs1.x = 1;30             cs1.y = 1;31             cs2.x = 2;32             cs2.y = 2;33 34             cs1 = cs2;35 36             Console.WriteLine("{0},{1}",cs2.x,cs2.y);37 38             cs2.x = 5;39 40             Console.WriteLine("{0},{1}", cs2.x, cs1.y);41 42             s1.x = 3;43             s1.y = 3;44             s2.x = 4;45             s2.y = 4;46 47             s1 = s2;48 49             Console.WriteLine("{0},{1}",s1.x,s1.y);50 51             s2.x = 6;52 53             Console.WriteLine("{0},{1}", s1.x, s1.y);54 55 56             Console.ReadKey();57         }58     }59 }

 

分別改變2號變數的值,會發現此時在類中,1號中的資料也會更改(實際上它們就是同一塊記憶體中的資料);但是結構體不會,因為兩個結構都是實值型別,無法進行引用傳遞,只能進行數值拷貝;

 

結構是隱式密封的,所有成員預設為private;同時無法被繼承,因此protected,virtual,abstruct,internal等修飾符不適用;

可以使用new建立執行個體,可以使用overried聲明覆寫;

 

其他類似與實值型別的操作適用於結構,例如out,ref參數類型等

 

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.