What does “var” mean in C#?
Possible Duplicate:
Use of var keyword in C#
在C中,关键字
这意味着编译器将推断声明的本地类型:
1 2 3 4 | // This statement: var foo ="bar"; // Is equivalent to this statement: string foo ="bar"; |
值得注意的是,
1 2 | var foo ="bar"; foo = 1; // Compiler error, the foo variable holds strings, not ints |
您不能将
它意味着数据类型是从上下文派生的(隐含的)。
来自http://msdn.microsoft.com/en-us/library/bb383973.aspx
Beginning 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. The
following two declarations of i are
functionally equivalent:
1 2 | var i = 10; // implicitly typed int i = 10; //explicitly typed |
1 |
变成
1 |
但也可能被过度使用到牺牲可读性的程度。
"var"表示编译器将根据用法确定变量的显式类型。例如,
1 |
会给你一个连接类型的变量。
它根据初始化中分配给它的内容声明一个类型。
一个简单的例子是,代码:
1 | var i = 53; |
将检查53的类型,并将其重写为:
1 | int i = 53; |
请注意,虽然我们可以:
1 | long i = 53; |
这不会发生在VaR中。尽管它可以发生在:
1 | var i = 53l; // i is now a long |
类似地:
1 2 | var i = null; // not allowed as type can't be inferred. var j = (string) null; // allowed as the expression (string) null has both type and value. |
对于复杂的类型,这可能是一个小的方便。匿名类型更重要:
1 2 3 | var i = from x in SomeSource where x.Name.Length > 3 select new {x.ID, x.Name}; foreach(var j in i) Console.WriteLine(j.ID.ToString() +":" + j.Name); |
这里没有其他方法可以定义
你不喜欢写这样的变量初始值设定项吗?
因此,从C 3.0开始,您可以将其替换为
注意:类型是在编译期间解决的,所以性能没有问题。但是编译器应该能够在构建步骤中检测类型,所以像