我刚刚开始在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 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.