# 隐式类型本地变量（C# 编程指南）Implicitly typed local variables (C# Programming Guide)

// i is compiled as an int
var i = 5;

// s is compiled as a string
var s = "Hello";

// a is compiled as int[]
var a = new[] { 0, 1, 2 };

// expr is compiled as IEnumerable<Customer>
// or perhaps IQueryable<Customer>
var expr =
from c in customers
where c.City == "London"
select c;

// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };

// list is compiled as List<int>
var list = new List<int>();


• 在局部变量（在方法范围内声明的变量）上，如前面的示例所示。On local variables (variables declared at method scope) as shown in the previous example.

• for 初始化语句中。In a for initialization statement.

for (var x = 1; x < 10; x++)

• foreach 初始化语句中。In a foreach initialization statement.

foreach (var item in list) {...}

• using 域间中。In a using statement.

using (var file = new StreamReader("C:\\myfile.txt")) {...}


## var 和匿名类型var and anonymous types

class ImplicitlyTypedLocals2
{
static void Main()
{
string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };

// If a query produces a sequence of anonymous types,
// then use var in the foreach statement to access the properties.
var upperLowerWords =
from w in words
select new { Upper = w.ToUpper(), Lower = w.ToLower() };

// Execute the query
foreach (var ul in upperLowerWords)
{
Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
}
}
}
/* Outputs:
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
*/


## 备注Remarks

• 仅当局部变量在相同语句中进行声明和初始化时，才能使用 var；变量不能初始化为 null，也不能初始化为方法组或匿名函数。var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

• var 不能在类范围内对字段使用。var cannot be used on fields at class scope.

• 使用 var 声明的变量不能在初始化表达式中使用。Variables declared by using var cannot be used in the initialization expression. 换句话说，此表达式是合法的：int i = (i = 20);，但是此表达式会生成编译时错误：var i = (i = 20);In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);

• 不能在相同语句中初始化多个隐式类型化变量。Multiple implicitly-typed variables cannot be initialized in the same statement.

• 如果一种名为 var 的类型处于范围内，则 var 关键字会解析为该类型名称，不会被视为隐式类型化局部变量声明的一部分。If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

var 关键字的隐式类型只能应用于本地方法范围内的变量。Implicit typing with the var keyword can only be applied to variables at local method scope. 隐式类型不可用于类字段，因为 C# 编译器在处理代码时会遇到逻辑悖论：编译器需要知道字段的类型，但它在分析赋值表达式前无法确定类型，而表达式在不知道类型的情况下无法进行计算。Implicit typing is not available for class fields as the C# compiler would encounter a logical paradox as it processed the code: the compiler needs to know the type of the field, but it cannot determine the type until the assignment expression is analyzed, and the expression cannot be evaluated without knowing the type. 考虑下列代码：Consider the following code:

private var bookTitles;


bookTitles 是类型为 var 的类字段。bookTitles is a class field given the type var. 由于该字段没有要计算的表达式，编译器无法推断出 bookTitles 应该是哪种类型。As the field has no expression to evaluate, it is impossible for the compiler to infer what type bookTitles is supposed to be. 此外，向该字段添加表达式（就像对本地变量执行的操作一样）也是不够的：In addition, adding an expression to the field (like you would for a local variable) is also insufficient:

private var bookTitles = new List<string>();


// Same as previous example except we use the entire last name as a key.
// Query variable is an IEnumerable<IGrouping<string, Student>>
var studentQuery3 =
from student in students
group student by student.Last;