我刚刚开始将 ReSharper 与 Visual Studio 结合使用(在收到许多关于 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 开发中,所以我真的很想了解正在发生的事情以及它是否有益。
I've just started using ReSharper with Visual Studio (after the many recommendations on SO). To try it out I opened up a recent ASP.NET MVC project. One of the first and most frequent things I've noticed it suggesting is to change most/all my explicit declarations to var
instead. For example:
//From This:
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
//To This:
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
and so on, even with simple types such as int
, bool
, etc.
Why is this being recommended? I don't come from a computer science or .NET background, having "fallen into" .NET development recently, so I'd really like to understand what's going on and whether it's of benefit or not.
发布评论
评论(23)
ReSharper 的建议显然是过度使用 var 关键字。您可以在类型明显的地方使用它:
如果类型不明显,您应该将其写出来:
What ReSharper suggests is clearly overuse of the var keyword. You can use it where the type is obvious:
If the type is not obvious, you should rather write it out:
原因之一是提高了可读性。哪个更好?
或者
One reason is improved readability. Which is better?
or
我个人更喜欢关闭这个建议。使用
var
通常可以提高可读性;但正如您所提到的,它有时会减少它(使用简单类型,或者当结果类型晦涩时)。我更喜欢选择何时使用
var
和何时不使用。但再说一遍,那只是我。I personally prefer to turn this suggestion off. Using
var
can often improve readability; but as you mentioned, it sometimes reduces it (with simple types, or when the resulting type is obscure).I prefer to choose when I use
var
and when I don't. But again, that's just me.var
可以提高代码的可读性,同时降低代码的即时理解性。同样,它会降低其他情况下代码的可读性。有时它的使用是中性的。可读性与理解性的衡量并不成正比,而是取决于具体情况。有时两者同时增加或减少。因素在于
var
的应用范围,以及目标对读者立即混淆其数据类型的支持程度,或者是否需要其类型信息来理解手头的程序部分。例如,错误的命名可能会导致
var
导致代码理解力下降。但这不是var
的错:有时,当代码在缺少它的情况下更具可读性时,将
var
用于简单数据类型是没有意义的:有时
var
可用于隐藏您不一定关心其复杂性的数据类型信息:当存在匿名类型时,您必须使用
var
因为没有类型名称来调用它:当您让 Visual Studio Intellisense 提供类型信息而不管
var
时,您就不需要通过严格的代码阅读而无需依赖于您的理解。明智的做法是假设并非每个人都拥有或使用 Intellisense。总之,根据上面的例子,我建议全权委托使用
var
并不是一个好主意,因为大多数事情最好根据具体情况适度完成。手如图所示。为什么Resharper默认全部使用它?我建议轻松一点,因为它无法解析情况的细微差别来决定何时最好不使用它。
var
can increase readability of code while decreasing immediate comprehension of the code. Just the same, it can decrease readability of the code for other situations. Sometimes the use of it is neutral. The measure of readability to comprehension isn't proportional but depends on the situation. Sometimes both are increased or decreased together.The factor is what
var
's being applied to and how well the target supports immediate obfuscation of its data type to the reader, or if its type info is needed to comprehend the program portion at hand.For example, bad naming can to lead to
var
causing decrease of code comprehension. This is notvar
's fault though:Sometimes it doesn't make sense to use
var
for simple data types when code is more readable in its absence:Sometimes
var
can be useful to hide data type information that you don't necessarily care to see the complexities of:You must use
var
when there's an anonymous type present because there's no type name to call it by:When you have Visual Studio Intellisense providing type information in spite of
var
, you then need to rely less on your understanding via strict code reading without an aid. It's probably wise to assume not everybody may have or use Intellisense.In summary based on the above examples, I'd suggest carte blanche application of
var
is not a good idea because most things are best done in moderation and based on the circumstance at hand as shown here.Why does Resharper use it all over by default? I'd suggest for ease, because it can't parse the nuances of situations to decide when best not to use it.
在 ReSharper(8.02,但也可能是其他版本)中,“使用隐式类型局部变量声明”建议的选项可以根据您的偏好进行调整,无论是什么,首先打开选项菜单ReSharper:
然后,在“代码检查”下,调整所选语言的“检查严重性”,在我的case c#:
如您所见,有一些选项可以调整 ReSharper 提出的所有建议。希望这可以帮助像我这样已经有了“var”使用策略并且只是希望 ReSharper 尊重它的人:)
In ReSharper (8.02, but likely other versions), the option for the "Use implicitly typed local variable declaration" suggestion can be adjusted to your preference, whatever that may be, by first opening the options menu for ReSharper:
Then, under "Code Inspection" by adjusting the "Inspection Severity" of your chosen language, in my case c#:
As you can see, there are options to adjust all the suggestions that ReSharper makes. Hopes this helps someone like me who already has a 'var' usage strategy and just wants ReSharper to respect it :)
'var' 是为了清晰
关于是否使用
var
关键字的主要争论在于代码对您和其他开发人员的可读性如何。就像你在写一个故事一样,没有明确的正确答案。但让我们用简单的英语来看一些例子。
谁走了另一条路?杰克还是比尔?在这种情况下,使用名称“Jake”和“Bill”就像使用类型名称一样。而“He”和“him”就像使用
var
关键字。在这种情况下,说得更具体可能会有所帮助。下面的例子就更清楚了。在这种情况下,更具体可以使句子更清晰。但情况并非总是如此。在某些情况下,具体化会使阅读变得更加困难。
在这种情况下,如果我们使用“he”,并且在某些情况下将他的名字全部省略,那么阅读句子会更容易,这相当于使用
var
关键字。这些例子涵盖了要点,但并没有讲述整个故事。在这些例子中,只有一种方式来指代这个人。要么使用他们的名字,要么使用更通用的术语,如“他”和“他”。
就代码而言,我们有 3 种方法来帮助提高清晰度。类型、变量名和赋值。以这行代码为例:
现在的问题是,这行代码中是否有足够的信息来帮助您弄清楚发生了什么?
下面这行代码怎么样?您是否仍然知道
p
在这种情况下意味着什么:现在怎么样:
或者现在:
或者这个:
或者这个:
关键字
var
在给定场景中是否有效取决于很多关于代码上下文的内容,例如变量、类和方法的命名方式。它还取决于代码及其周围代码的其余部分的复杂性。就我个人而言,我喜欢使用
var
关键字,它在大多数时候对我来说更全面。但我也倾向于根据类型命名我的变量,这样我就不会真正丢失任何信息。也就是说,有时根据具体情况,我会做出例外,这就是任何复杂事物的本质,而软件如果不复杂就什么都不是。
'var' is about being clear
The main debate about whether to use the
var
keyword or not is about how readable the code is to you and other developers.Just as if you were writing a story there is not definitive right answer. But let's look at some examples of this in plain English.
Who went the other way? Jake or Bill? In this case using the names "Jake" and "Bill" is like using the type name. And "He" and "him" is like using the
var
keyword. In this case it might help to be more specific. The following for example is much clearer.In this case being more specific made the sentence clearer. But that's not always going to be case. In some cases being specific makes it harder to read.
In this case it would be easier to read the sentence if we used "he" and in some cases left out his name all together, which is the equivalent of using the
var
keyword.Those examples cover the gist, but they don't tell the whole story. In those examples there was only one way to refer to the person. Either by using their name or by using a more general term like "he" and "him".
In the case of code we have 3 ways we to help add clarity. The type, the variable name, and the assignment. Take this line of code for example:
The question now becomes is there enough information in that line of code to help you figure out what's going on?
What about the following line of code? Would you still know what
p
means in this case:How about now:
Or now:
Or this one:
Or this:
Whether the keyword
var
works in a given scenario depends a lot on the context of the code, like how the variables, classes, and methods are named. It also depends on the complexity of the code and the rest of the code surrounding it.Personally I like to use the
var
keyword it's more comprehensive to me most of the time. But I also tend to name my variables after the type so I'm not really losing any information.That said sometimes depending on the context I make exceptions, such is the nature of anything complex, and software is nothing if not complex.
令我惊讶的是,没有人提到更改实例化对象的类型也更容易,因为它
是一种重复形式。如果我想将 AVeryLongTypeName 更改为其派生类之一,则在使用 var 时只需更改一次,并且仍然可以访问子类的方法。
除此之外,提高可读性是很重要的一点,但正如其他人所说,var 不应该被过度使用,所以我认为在 Resharper 中关闭提示是绝对可以的。
I am surprised that nobody mentioned that it is also easier to change the type of the instantiated object, because
is a form of repetition. If I want to change
AVeryLongTypeName
into one of its derived classes, I need only change this once when usingvar
and still can access methods of the child classes.Aside from that, the improved readability is an important point, but as others said, var should not be overused, so I think turning the hint off in Resharper is absolutely ok.
我也不喜欢这个。
我不希望这变成关于 var 的使用的争论,它有它的用途,但不应该在任何地方使用。
要记住的关键一点是 ReSharper 可以根据您想要的任何编码标准进行配置。
编辑:ReSharper 和 var
I disliked this as well.
I dont want this to turn into a debate on the use of
var
, it has its uses but should not be used everywhere.The key thing to remember is ReSharper is configured to whatever coding standards you want.
Edit: ReSharper and var
我看到了很多正确答案,但缺少完整的答案。
确实,ReSharper 默认情况下过度使用
var
。我想大多数人都会同意这一点。当使用var
并且类型很明显时(例如当您使用new
语句时),它也更容易阅读。我看到一篇文章展示了如何更新检查严重性以仅显示使用var
的提示。我曾尝试先对其他帖子发表评论,以添加设置这些帖子的位置,但没有声誉。显然,我也没有资格发布我的设置屏幕截图。
我将解释如何到达那里。
在 Visual Studio 中>主菜单>重磨器>选项>代码编辑> C#>代码风格>声明中的 Var 使用
ReSharper 帮助文档:代码语法风格:隐式/显式键入('var' 关键字)
— 配置使用“var”关键字的首选项
I see many correct answers, but missing the full one.
It is true that ReSharper overuses
var
by default. I think most people would agree with that. It is also easier to read whenvar
is used and the type is obvious such as when you use anew
statement. I saw one post that showed how to update inspection severity to only show hints for the use ofvar
.I had tried to comment on other posts first to add where to set these but didn't have the reputation for it. Apparently, I also didn't have the reputation to post my screenshot of the settings.
I will explain how to get there.
In Visual Studio > Main Menu > Resharper > Options > Code Editing > C# > Code Style > Var Usage in declarations
ReSharper help documentation: Code Syntax Style: Implicit/Explicit Typing ('var' Keyword)
— Configure preferences of using 'var' keyword
我的规则是这样的:
你是否声明一个基本类型(即
byte
、char
、string
、int[]< /code>、
双精度?
、十进制
等)? ->使用类型:您是否声明了复杂类型(即
List
、Dictionary
、MyObj
) ? ->使用var
:My rule is this:
Are you declaring a primitive type (i.e.
byte
,char
,string
,int[]
,double?
,decimal
, etc.)? -> Use the type:Are you declaring a complex type (i.e.
List<T>
,Dictionary<T, T>
,MyObj
)? -> Usevar
:我只想指出 C# 编码约定
这可能就是 ReSharper 中默认打开提示的原因。他们还在同一文档的下面提供了一些不会提高可读性的情况。
I'd just like to point that the use of "var" is recommended in the C# Coding Conventions
so that's probably why the tip is on by default in ReSharper. They also provide some cases where it would not improve readability right below in the same document.
ReSharper 建议使用
var
,因为它可以使对象创建更加整洁。比较这两个例子:
这只是一个简写,应该更容易阅读。
我认为当你用“new”显式创建新对象时就很好了。然而,在您的示例中,如果类命名不正确,可能并不明显。
ReSharper recommends
var
because it tends to unclutter object creation.Compare these two examples:
It's just a shorthand that is supposed to be easier to read.
I think it's fine when you create new objects explicitly with "new". In your example however, it might not be obvious if the classes were not named properly.
瓦尔太棒了!我遇到过许多开发人员,他们的印象是
var
绑定到动态类型,但事实并非如此。它仍然是静态类型,只是由编译器决定。以下是使用 var 的一些令人惊奇的优点
减少输入 var 更短且更易于阅读,例如
Dictionary> postcodes = new Dictionary>()
Yuk.var postcodes = new Dictionary>()
\o/\o/更具描述性的变量名称 - 很脆弱,但我认为让
var
的流动性在这里发挥作用很重要。由于var
有点模糊,它确实鼓励使用更具描述性的变量名称,而不是让类型自己说话。更少的代码更改 - 如果方法调用的返回类型发生更改。您只需更改方法调用,而不是使用它的每个地方。
匿名类型 - 匿名类型是一个非常强大的概念,特别是在 WebApi 等领域 部分资源。没有 var,它们就无法使用。
然而,有时显式声明类型很有用,我发现这在基元或结构中最有用。例如,我个人认为这种语法不是很有用:
vs
这完全取决于个人喜好,但使用
var
确实会加快您的开发速度并解锁匿名类型的整个世界。Var is amazing! I have come across many a developer who are under the impression that
var
is bound to a dynamic type, it is not. It is still statically typed, it's just decided by the compiler.Here are some amazing positives of using var
Less typing var is shorter and easier to read, for instance
Dictionary<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. Asvar
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.
Sometimes however it is useful to explictly declare types and I find this most useful in primitives or structs. For instance, I don't personally find this syntax very useful:
vs
It's all down to personal preference but using
var
really will speed up your development and unlock a whole world of anonymous type goodness.顺便说一句,ReSharper 区分了“您可能希望将此建议应用于您的代码”和“您的代码已损坏,需要我修复它吗?”。
var
关键字位于建议类别中,以及“反转 if 以减少嵌套”等内容;你不必遵循它。您可以通过“选项”对话框或直接通过该警报的弹出菜单来配置每个警报的烦人程度。您可以降级诸如
var
建议之类的内容,使其不那么突出,或者您可以升级诸如“使用扩展方法”警报之类的内容,使其显示为实际错误。BTW, ReSharper draws a distinction between 'you might want to apply this suggestion to your code' and 'your code is broken, want me to fix it?'. The
var
keyword is in the suggestion category, along with things like "invert if to reduce nesting"; you don't have to follow it.You can configure how annoying each of its alerts are through the Options dialog, or directly through the popup menu for that alert. You can downgrade things like the
var
suggestion so they're less prominent, or you can upgrade things like the 'use extension method' alert so it shows up as an actual error..NET 3.0 的
var
功能只是 类型推断,它是类型安全的,通常使您的代码更易于阅读。但您不必这样做,并且如果您愿意,可以在 ReSharper 中关闭该建议。The
var
feature of .NET 3.0 is just type inference, which is type-safe and often makes your code easier to read. But you don't have to, and can turn that recommendation off in ReSharper if you want.在我看来,只有在定义变量的值时立即清楚类型是什么时才应使用
var
。示例:
很明显
s
是一个字符串
。我相信当变量类型名称非常复杂时它也是合适的。
示例:
除了这些场景之外,我没有看到使用
var 能带来任何增益
code>,但我可以想到一些可能有害的场景:
例如,一次性类型的右侧变量值没有清楚地显示类型。 IDisposable 的处置很容易被忘记
示例:
In my view,
var
should only be used when it is immediately clear what the type is when defining the value of the variable.Example:
It is obvious that
s
is astring
.I believe it is also appropriate when the variable type name is very complex.
Example:
Other than these scenarios, I don't see any GAIN to be made by using
var
, but I can think of some scenarios in which it can be detrimental:For example, a disposable type whose right-hand-side variable value does not clearly show the type. Disposing of the IDisposable can easily be forgotten about
Example:
没有技术上的区别,如果您使用 var,则类型由编译器隐含。如果您有这样的代码:
x 隐含为 int 并且不能为其分配其他值。
如果您更改变量的类型,则 var 关键字很有用;然后您只需进行一项更改,而不是两项:
There is no technical difference, if you use var, the type is implied by the compiler. If you have a code like this:
x is implied to be an int and no other values can be assigned to it.
The var keyword is useful if you change the type of the variable; you then only have to make one change instead of two:
var
关键字是在 C# 3.0 中引入的 - 它允许我们忘记显式指定类型。没有真正的区别
使用
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
或
var foo = DB.MyObjects.SingleOrDefault( w => w.Id == 1);
除了纯粹的可读性和更少的错误机会。
这看起来像是一个陈词滥调的例子,但是说下面的内容可能会帮助你理解:
返回一个
int
类型,而返回一个
string
类型。MSDN 参考
The
var
keyword was introduced in C# 3.0 - it allows us to forget about specifying our type explicitly.There is no real difference to whether you use
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
or
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
except pure readability and less chance for error.
It seems like a clichéd example, but say the following may help your understanding:
returns an
int
type, whereasreturns a
string
type.MSDN reference
指定显式对象类型在某种程度上是多余的。即使翻译成英语,它听起来也是多余的:“将 X 类型的对象放入 X 类型的变量中”与“将 X 类型的对象放入变量中”。
但是,使用“var”有其局限性。它阻止了多态性的以下使用,这是纯粹的美:
假设一只狗继承了动物; Cat 扩展了 Animal 类层次结构:
相同的代码,其中 x 用“var”声明将无法编译。
无论如何,回到最初的问题,我不使用 Resharper,但我认为它足够聪明,可以检测何时不使用“var”。 :-)
Specifying an explicit object type is somehow redundant. Even translated in english, the it sounds redundant: "put an object of type X in a variable of type X" vs "Put an object of type X in a variable".
However, using 'var' has its limitations. It prevents the below usage of polymorphism which is pure beauty:
Assume an Dog extends Animal; Cat extends Animal class hierarchy:
The same code, with x declared with 'var' will not compile.
Anyways, back to the original question, I don't use Resharper, but I assume that is is smart enough to detect when to not use 'var'. :-)
没有技术差异(正如 eWolf 指出的)。您可以使用其中之一,生成的 CLR 代码看起来是一样的。
在我看来,主要的好处是这往往会迫使您使用更好的变量命名。在您的示例中,“foo”对于变量名来说是一个非常糟糕的选择。
There is no technical difference (as eWolf pointed out). You can use one or the other, the generated CLR code will look the same.
In my opinion the main benefit is that this tends to force you to use better variable naming. In your example 'foo' is a pretty poor choice for a variable name.
'var' 向您的代码添加了一种“动态”元素(尽管代码当然仍然是严格类型化的)。我建议不要在类型不清楚的情况下使用它。考虑这个例子:
如果 GetTheObjectFromDatabase() 的返回类型从类型 A 更改为类型 B,我们不会注意到,因为这两个类都实现了 DoSomething()。然而,现在的代码实际上可能会执行完全不同的操作。
这可能与将不同的内容写入日志一样微妙,因此您可能不会注意到,直到为时已晚。
var 的以下使用应该总是没问题的:
'var' adds a kind of "dynamic" element to your code (although the code remains of course strictly typed). I advice against using it in cases where the type is not clear. Consider this example:
Should the return Type of GetTheObjectFromDatabase() be changed from Type A to B we will not notice, since both Classes implement DoSomething(). The code, however, may now actually do something entirely different.
This may be as subtle as both writing different stuff to a log, so you might not notice unitl it's too late.
The following use of var should always be fine:
对于那些不喜欢不断使用“var”的人,您还可以阻止 ReSharper 在执行“引入变量”时默认为 var。这是让我沮丧了很长一段时间的事情,它总是默认为var,而我每次都在改变它。
这些设置位于“代码编辑”>“代码编辑”下。 C#>代码风格
For those that dislike the constant use of "var", you can also stop ReSharper from defaulting to var when doing "introduce variable". This was something that frustrated me for a long time, it was always defaulting to var, and I was changing it every time.
These settings are under Code Editing > C# > Code Style
根据 JetBrains(ReSharper 的作者)的说法,他们鼓励默认使用 var。
来自他们的网站:
According to JetBrains (the author of ReSharper), they encourage the use of var by default.
From their website: