我刚刚开始在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的一些惊人的优点

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真的会加速你的开发,并打开一个匿名类型的美好世界。

其他回答

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

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

顺便说一句,ReSharper在“你可能想把这个建议应用到你的代码中”和“你的代码坏了,想让我修复它吗?”之间做了区分。var关键字在建议类别中,与“反转if以减少嵌套”一样;你不必遵循它。

你可以通过“选项”对话框,或者直接通过弹出菜单来设置每个警报的恼人程度。你可以降级像var建议这样的东西,让它们不那么突出,或者你可以升级像“使用扩展方法”警告这样的东西,让它显示为一个实际的错误。

我看到了许多正确答案,但没有完整的答案。

ReSharper确实在默认情况下过度使用var。我想大多数人都会同意这一点。当使用var并且类型很明显时(例如使用new语句时),它也更容易阅读。我看到一篇文章展示了如何更新检查的严重性,只显示使用var的提示。

我曾尝试在其他帖子上评论,添加在哪里设置这些,但没有这样的声誉。显然,我也没有名声发布我的设置截图。

我会解释怎么去那里。

在Visual Studio >主菜单> Resharper > Options > Code Editing > c# > Code Style > Var using In declarations

对于内置类型使用显式类型 对于简单类型,在明显时使用'var' 在其他地方使用'var '

ReSharper帮助文档:代码语法风格:隐式/显式类型('var'关键字) -配置使用'var'关键字的首选项

在我看来,只有在定义变量值时立即清楚该变量的类型时才应该使用var。

例子:

var s = "string value";

很明显,s是一个字符串。

我相信当变量类型名称非常复杂时,这也是合适的。

例子:

Dictionary<SomeCustomKeyType, Dictionary<AnotherCustomKeyType, List<int>>> dict = new Dictionary<SomeCustomKeyType, Dictionary<AnotherCustomKeyType, List<int>>>();

// This is a little easier to read than the above statement
var dict = new Dictionary<SomeCustomKeyType, Dictionary<AnotherCustomKeyType, List<int>>>();

除了这些情况,我不认为使用var有任何好处,但我可以想到一些情况下它可能是有害的:

例如,一个一次性类型的右侧变量值没有清楚地显示该类型。一次性用品的处理很容易被遗忘

例子:

// returns some file writer
var wr = GetWriter();

wr.add("stuff");
wr.add("more stuff");

//...
//...

// Now `wr` needs to be disposed, 
// but there is no clear indication of the type of `wr`,
// so it will be easily overlooked by code writer and code reviewer.

指定显式对象类型在某种程度上是多余的。即使用英语翻译,它听起来也是多余的:“将X类型的对象放入X类型的变量中”vs“将X类型的对象放入变量中”。

然而,使用'var'有其局限性。它防止了以下纯美的多态用法:

假设狗伸展动物;Cat扩展了动物等级:

Animal x = new Dog();
DoStuffWithDog(x as Dog);

x = new Cat();
DoStuffWithCat(x as Cat);

void DoStuffWithDog(Dog d){}
void DoStuffWithCat(Cat c){}

同样的代码,用'var'声明x将无法编译。

var x = new Dog(); // from this point, x is a Dog
DoStuffWithDog(x as Dog);

x = new Cat(); // cannot assign a Cat instance to a Dog
DoStuffWithCat(x as Cat);

void DoStuffWithDog(Dog d){}
void DoStuffWithCat(Cat c){}

无论如何,回到最初的问题,我不使用Resharper,但我假设它足够智能,可以检测到什么时候不使用'var'。: -)