| 特性 | 類別 | 結構 |
|---|---|---|
| 型別分類 | 參考型別 | 值型別 |
| 繼承 | 支援 | 不支援(隱性繼承 ValueType) |
| 記憶體配置 | 堆積 | 堆疊或內嵌 |
| 預設值 | null | 零值初始化 |
| 參數傳遞 | 傳參考 | 傳值(複製) |
建立 100 個 Point 陣列元素:
// 類別版:101 個物件(1 陣列 + 100 元素)
class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }
Point[] points = new Point[100];
for (int i = 0; i < 100; i++) points[i] = new Point(i, i*i);
// 結構版:僅 1 個陣列物件,元素內嵌配置
struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }
Point[] points = new Point[100];
for (int i = 0; i < 100; i++) points[i] = new Point(i, i*i);
結構是效能優化工具,而非銀彈。決策前請先分析具體使用情境與基準測試。