var 是 C# 3.0 引入的隱式型別區域變數宣告關鍵字。它指示編譯器根據初始化運算式自動推斷變數型別,生成的 IL 與顯式型別宣告完全相同。本文詳細整理推斷規則、五大限制、陣列推斷與團隊編碼風格建議。
var integer = 10; // int
var name = "edisundong"; // string
var numbers = new int[] { 1, 2, 3 }; // int[]
var anon = new { X = 1, Y = 2 }; // 匿名類型
| # | 限制 | 錯誤代碼 | 編譯錯誤訊息 |
|---|---|---|---|
| 1 | 必須初始化 | var x; x = 10; | 隱式型別區域變數必須已初始化 |
| 2 | 不可為 null | var x = null; | 無法將 <null> 指派給隱式型別區域變數 |
| 3 | 強型別不可變 | var x = 10; x = "abc"; | 無法將型別 'string' 隱式轉換為 'int' |
| 4 | 初始化器必為運算式 | var x = { A = 1 }; | 無法從初始化器推斷型別 |
| 5 | 僅限區域變數 | class C { var f = 1; } | "var" 關鍵字只能出現在區域變數宣告中 |
var a = new[] { 1, 10, 100 }; // int[]
var b = new[] { "hello", "world" }; // string[]
var c = new[] { new[]{1,2}, new[]{3,4} }; // int[][]
// var d = new[] { 1, "str" }; // 錯誤:元素型別不相容
規則:所有元素必須隱式可轉換至單一共同型別。
for (var i = 0; i < 10; i++)foreach (var item in list)using (var fs = File.OpenRead(...))var list = new List<string>();var dict = new Dictionary<string, List<int>>();var x = 10; 不如 int x = 10; 明確var result = Calculate(); 維護者需查閱方法簽章IEnumerable<int> nums = GetNumbers(); 比 var nums = GetNumbers(); 表達設計意圖在 .editorconfig 或程式碼風格規範中明確定義:
# .editorconfig 範例
csharp_style_var_for_built_in_types = false:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = false:suggestion
統一風格可減少程式碼審查爭議,提升團隊協作效率。