我刚刚开始在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开发,所以我真的很想了解正在发生什么,以及它是否有益。


当前回答

我的原则是:

你是否声明了一个基本类型(即字节,char,字符串,int[], double) ?,十进制,等等)?->类型: string myStr = "foo"; int[] myIntArray = [123, 456, 789]; 双吗?myDouble = 123.3; 您是否声明了一个复杂类型(即List<T>, Dictionary<T, T>, MyObj)?->使用var: var myList =列表<字符串>(); var myDictionary = Dictionary<string, string>(); var myObjInstance = new MyObj();

其他回答

瓦尔太棒了!我遇到过许多开发人员,他们认为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真的会加速你的开发,并打开一个匿名类型的美好世界。

我只是想指出,在c#编码约定中推荐使用“var”

当变量的类型从赋值的右边很明显时,或者当精确的类型不重要时

所以这可能是ReSharper默认开启提示的原因。它们还提供了一些在同一文档的正下方不会提高可读性的情况。

我也不喜欢这样。

我不希望这变成一场关于var使用的争论,它有它的用途,但不应该到处使用。

要记住的关键是ReSharper被配置为你想要的任何编码标准。

编辑:ReSharper和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.

ReSharper推荐var,因为它倾向于整理对象创建。

比较这两个例子:

StringBuilder bld = new StringBuilder();

var bld = new StringBuilder();

这只是一种简写,应该更容易阅读。

我认为,当你显式地用“new”创建新对象时,这很好。然而,在您的示例中,如果类没有正确命名,可能就不那么明显了。