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


当前回答

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

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

or

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

其他回答

指定显式对象类型在某种程度上是多余的。即使用英语翻译,它听起来也是多余的:“将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'。: -)

在我看来,只有在定义变量值时立即清楚该变量的类型时才应该使用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.

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

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

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

我的原则是:

你是否声明了一个基本类型(即字节,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”的人,你也可以在执行“引入变量”时停止ReSharper默认使用var。这让我很长一段时间都很沮丧,它总是默认为var,而我每次都在改变它。

这些设置在代码编辑> c# >代码样式下