var(C# 参考)var (C# Reference)

从 Visual C# 3.0 开始,在方法范围内声明的变量可以具有隐式“类型”varBeginning in Visual C# 3.0, variables that are declared at method scope can have an implicit "type" var. 隐式类型本地变量为强类型,就像用户已经自行声明该类型,但编译器决定类型一样。An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. i 的以下两个声明在功能上是等效的:The following two declarations of i are functionally equivalent:

var i = 10; // Implicitly typed.
int i = 10; // Explicitly typed.

有关详细信息,请参阅隐式类型的局部变量LINQ 查询操作中的类型关系For more information, see Implicitly Typed Local Variables and Type Relationships in LINQ Query Operations.

示例Example

下面的示例演示两个查询表达式。The following example shows two query expressions. 在第一个表达式中,var 的使用是允许的,但不是必需的,因为查询结果的类型可以明确表述为 IEnumerable<string>In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>. 不过,在第二个表达式中,var 允许结果是一系列匿名类型,且相应类型的名称只可供编译器本身访问。However, in the second expression, var allows the result to be a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. 如果使用 var,便无法为结果新建类。Use of var eliminates the requirement to create a new class for the result. 请注意,在示例 #2 中,foreach 迭代变量 item 必须也为隐式类型。Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

// Example #1: var is optional when
// 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);
}

请参阅See also