我刚刚开始在Visual Studio中使用ReSharper(在SO上的许多建议之后)。为了尝试一下,我打开了一个最近的ASP。NET MVC项目。我注意到它建议的第一件也是最频繁的事情之一是将我的大部分/所有显式声明改为var。例如:

//From This:
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
//To This:
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);

等等,即使是简单的类型,如int, bool等。

为什么推荐这个?我没有计算机科学或。net背景,最近“陷入”了。net开发,所以我真的很想了解正在发生什么,以及它是否有益。


当前回答

我个人倾向于关闭这个建议。使用var通常可以提高可读性;但正如您所提到的,它有时会减少它(使用简单类型,或当结果类型不明确时)。

我更喜欢选择什么时候用var,什么时候不用。但这只是我的看法。

其他回答

其中一个原因是可读性的提高。哪个更好?

Dictionary<int, MyLongNamedObject> dictionary = new Dictionary<int, MyLongNamedObject>();

or

var dictionary = new Dictionary<int, MyLongNamedObject>();

'var'为你的代码添加了一种“动态”元素(尽管代码仍然是严格类型的)。我建议不要在类型不清楚的情况下使用它。想想这个例子:

var bar = GetTheObjectFromDatabase();
bar.DoSomething();

ClassA {
  void DoSomething() {
  //does something
  }
}

ClassB {
  void DoSomething() {
  //does something entirely different
  }
}

如果GetTheObjectFromDatabase()的返回类型从Type A更改为B,我们不会注意到,因为这两个类都实现了DoSomething()。然而,现在的代码实际上可能做一些完全不同的事情。

这可能就像在日志中写入不同的内容一样微妙,所以您可能不会注意到,直到为时已晚。

var的以下用法应该总是正确的:

var abc = new Something();

我个人倾向于关闭这个建议。使用var通常可以提高可读性;但正如您所提到的,它有时会减少它(使用简单类型,或当结果类型不明确时)。

我更喜欢选择什么时候用var,什么时候不用。但这只是我的看法。

ReSharper的建议显然是过度使用var关键字。你可以在类型很明显的地方使用它:

var obj = new SomeObject();

如果类型不明显,你应该写出来:

SomeObject obj = DB.SomeClass.GetObject(42);

瓦尔太棒了!我遇到过许多开发人员,他们认为var是绑定到动态类型的,但事实并非如此。它仍然是静态类型的,只是由编译器决定。

下面是使用var的一些惊人的优点

Less typing var is shorter and easier to read, for instanceDictionary<int,IList<string>> postcodes = new Dictionary<int,IList<string>>() Yuk. var postcodes = new Dictionary<int,IList<string>>() \o/\o/ More descriptive variable names - tenuous one but I think its important to let the fluid nature of var shine here. As var is a bit vague, it really does encourage a more desciptive variable name rather than letting the type speak for itself. Less code changes - if the return type of a method call changes. You only have to change the method call, not every place it’s used. Anonymous types - anonymous types are a really powerful concept, especially in areas such as WebApi partial resources. Without var, they cannot be used.

然而,有时显式声明类型是有用的,我发现这在原语或结构中最有用。例如,我个人不觉得这个语法很有用:

for(var i = 0; i < 10; i++) 
{

}

vs

for(int i = 0; i < 10; i++) 
{

}

这完全取决于个人喜好,但使用var真的会加速你的开发,并打开一个匿名类型的美好世界。