var (C# 參考)

更新:2007 年 11 月

在方法範圍宣告的變數具有隱含型別 var。隱含型別區域變數是強型別 (Strongly Typed),就和您自行宣告型別一樣,差別在於前者是由編譯器 (Compiler) 判斷型別。下列兩個 i 宣告的功能相同:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

如需詳細資訊,請參閱隱含型別區域變數 (C# 程式設計手冊)查詢作業中的型別關聯性 (LINQ)

範例

下列範例顯示兩個查詢運算式。在第一個運算式中,因為查詢結果的型別可以明確陳述為 IEnumerable<string>,所以允許使用 var,但不需要這麼做。而在第二個運算式中,因為結果是匿名型別的集合,而且只有編譯器 (Compiler) 才可以存取該型別的名稱,所以必須使用 var。請注意,在第二個範例中,foreach 反覆運算變數 item 也必須是隱含型別。

// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}

請參閱

概念

C# 程式設計手冊

參考

隱含型別區域變數 (C# 程式設計手冊)

其他資源

C# 參考