C#中"var"的含义是什么?

ala*_*a27 90 c#

可能重复:
在C#中使用var关键字

在C#中,关键字" var " 如何工作?

cdh*_*wie 158

这意味着声明的本地类型将由编译器推断:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";
Run Code Online (Sandbox Code Playgroud)

值得注意的是,var没有将变量定义为动态类型.所以这不合法:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints
Run Code Online (Sandbox Code Playgroud)

var 只有两个用途:

  1. 声明变量需要较少的输入,特别是在将变量声明为嵌套泛型类型时.
  2. 在存储对匿名类型对象的引用时必须使用它,因为事先无法知道类型名称: var foo = new { Bar = "bar" };

您不能使用var除本地人之外的任何类型.所以你不能使用关键字var来声明field/property/parameter/return类型.

  • @Djack这不合法,事实并非如此.`var foo = new Foo();`与`Foo foo = new Foo();`是一回事,这意味着`foo`可以包含一个`Foo`引用,或者一个对象的引用任何`Foo`**sub**type,*not*a`Foo`**super**type. (3认同)

Red*_*ter 15

这意味着数据类型是从上下文派生(隐含)的.

来自http://msdn.microsoft.com/en-us/library/bb383973.aspx

从Visual C#3.0开始,在方法范围声明的变量可以具有隐式类型var.隐式类型的局部变量是强类型的,就像您自己声明了类型一样,但编译器确定了类型.以下两个i声明在功能上是等效的:

var i = 10; // implicitly typed
int i = 10; //explicitly typed
Run Code Online (Sandbox Code Playgroud)

var 对于消除键盘输入和视觉噪音很有用,例如,

MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();
Run Code Online (Sandbox Code Playgroud)

var x = new MyReallyReallyLongClassName();
Run Code Online (Sandbox Code Playgroud)

但可以过度使用到牺牲可读性的程度.


aaa*_*bbb 8

"var"表示编译器将根据用法确定变量的显式类型.例如,

var myVar = new Connection();
Run Code Online (Sandbox Code Playgroud)

会给你一个Connection类型的变量.


Jon*_*nna 7

它根据初始化中分配给它的内容声明了一个类型.

一个简单的例子是代码:

var i = 53;
Run Code Online (Sandbox Code Playgroud)

将检查53的类型,并基本上将其重写为:

int i = 53;
Run Code Online (Sandbox Code Playgroud)

请注意,虽然我们可以:

long i = 53;
Run Code Online (Sandbox Code Playgroud)

var不会发生这种情况.虽然它可以用:

var i = 53l; // i is now a long
Run Code Online (Sandbox Code Playgroud)

同理:

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.
Run Code Online (Sandbox Code Playgroud)

对于复杂类型,这可能是一个小的便利.匿名类型更重要:

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);
Run Code Online (Sandbox Code Playgroud)

这里没有其他方式来定义ij使用var,因为它们所拥有的类型没有名称.


The*_*est 5

您是否曾经讨厌编写这样的变量初始值设定项?

XmlSerializer xmlSerializer = new XmlSerialzer(typeof(int))
Run Code Online (Sandbox Code Playgroud)

因此,从C#3.0开始,您可以将其替换为

var xmlSerializer = new XmlSerialzer(typeof(int))
Run Code Online (Sandbox Code Playgroud)

注意:类型在编译过程中已解决,因此性能没有问题。但是Compiler应该能够在构建步骤中检测类型,因此类似的代码var xmlSerializer;根本不会编译。