C# 中的結構型別(struct)
阿新 • • 發佈:2019-01-01
有時候,類中只包含極少的資料,因為管理堆而造成的開銷顯得極不合算。這種情況下,更好的做法是使用結構(struct)型別。由於 struct 是值型別,是在棧(stack)上儲存的,所以能有效的減少記憶體管理的開銷(當然前提是這個結構足夠小)。
結構可以包含它自己的欄位、方法和構造器。
int 實際上是 Sysytem.Int32 結構型別。
編譯器始終會生成一個預設的構造器,若自己寫預設構造器則會出錯(預設構造器始終存在)。自己只能寫非預設構造器,並且在自己寫的構造器中初始化所有欄位。
- struct Time
- {
- public Time()
- {
-
// 編譯時錯誤:Structs cannot contain explicit parameterless constructors
- }
- }
- struct NewYorkTime
- {
- privateint hours, minutes, seconds;
- public NewYorkTime(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- } // 編譯時錯誤,因為 seconds 未初始化
- }
可以使用 ? 修飾符建立一個結構變數的可空(nullable)的版本。然後把 null 值賦給這個變數。
- using System;
-
using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace structType
- {
- class Program
- {
- staticvoid Main(string[] args)
- {
- NewYorkTime? currentTime = null; // 結構型別也是值型別,可以宣告為可空
- }
- }
- struct NewYorkTime
- {
-
privateint hours, minutes, seconds;
- public NewYorkTime(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- seconds = 0;
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace structType
- {
- class Program
- {
- staticvoid Main(string[] args)
- {
- Time now = new Time(); // 呼叫預設構造器,從而自動初始化,所有欄位為 0
- }
- }
- struct Time
- {
- privateint hours, minutes, seconds;
- }
- }
欄位(field)值如下:
下面這種方式,結構將不會被初始化,但是也不能訪問。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace structType
- {
- class Program
- {
- staticvoid Main(string[] args)
- {
- Time now; // 不進行初始化,若訪問欄位的值會造成編譯錯誤
- }
- }
- struct Time
- {
- privateint hours, minutes, seconds;
- }
- }
自己定義的構造器必須在構造器內把所有的欄位初始化。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace structType
- {
- class Program
- {
- staticvoid Main(string[] args)
- {
- Time now = new Time(12, 30);
- }
- }
- struct Time
- {
- privateint hours, minutes, seconds;
- public Time(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- seconds = 0;
- }
- }
- }
結構中的欄位不能在宣告的同時進行初始化。
- struct Time
- {
- privateint hours = 0; // 報錯 'Time.hours': cannot have
- // instance field initializers in structs
- privateint minutes, seconds;
- public Time(int hh, int mm)
- {
- hours = hh;
- minutes = mm;
- seconds = 0;
- }
- }