为什么ReSharper要使用'var'为了一切?

发布于 2024-08-13 13:55:51 字数 463 浏览 6 评论 0 原文

我刚刚开始将 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);

等等,甚至是简单的类型,如 intbool 等。

为什么推荐这样做?我没有计算机科学或 .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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

染年凉城似染瑾 2024-08-20 13:55:51

ReSharper 的建议显然是过度使用 var 关键字。您可以在类型明显的地方使用它:

var obj = new SomeObject();

如果类型不明显,您应该将其写出来:

SomeObject obj = DB.SomeClass.GetObject(42);

What ReSharper suggests is clearly overuse of the var keyword. You can use it where the type is obvious:

var obj = new SomeObject();

If the type is not obvious, you should rather write it out:

SomeObject obj = DB.SomeClass.GetObject(42);
难如初 2024-08-20 13:55:51

原因之一是提高了可读性。哪个更好?

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

或者

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

One reason is improved readability. Which is better?

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

or

var dictionary = new Dictionary<int, MyLongNamedObject>();
风向决定发型 2024-08-20 13:55:51

我个人更喜欢关闭这个建议。使用 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.

从此见与不见 2024-08-20 13:55:51

var 可以提高代码的可读性,同时降低代码的即时理解性。同样,它会降低其他情况下代码的可读性。有时它的使用是中性的。可读性与理解性的衡量并不成正比,而是取决于具体情况。有时两者同时增加或减少。

因素在于 var 的应用范围,以及目标对读者立即混淆其数据类型的支持程度,或者是否需要其类型信息来理解手头的程序部分。

例如,错误的命名可能会导致 var 导致代码理解力下降。但这不是 var 的错:

var value1 = GetNotObviousValue(); //What's the data type? 
//vs. 
var value2 = Math.Abs(-3); // Obviously a numeric data type. 

有时,当代码在缺少它的情况下更具可读性时,将 var 用于简单数据类型是没有意义的:

var num = GetNumber(); // But what type of number?
// vs. 
double num = GetNumber(); // I see, it's a double type. 

有时 var 可用于隐藏您不一定关心其复杂性的数据类型信息:

    IEnumerable<KeyValuePair<string,List<Dictionary<int,bool>>>> q = from t in d where t.Key == null select t; // OMG! 
    //vs. 
    var q = from t in d where t.Key == null select t;

    // I simply want the first string, so the last version seems fine.  
    q.First().Key; 

当存在匿名类型时,您必须使用var因为没有类型名称来调用它:

var o = new { Num=3, Name="" };

当您让 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 not var's fault though:

var value1 = GetNotObviousValue(); //What's the data type? 
//vs. 
var value2 = Math.Abs(-3); // Obviously a numeric data type. 

Sometimes it doesn't make sense to use var for simple data types when code is more readable in its absence:

var num = GetNumber(); // But what type of number?
// vs. 
double num = GetNumber(); // I see, it's a double type. 

Sometimes var can be useful to hide data type information that you don't necessarily care to see the complexities of:

    IEnumerable<KeyValuePair<string,List<Dictionary<int,bool>>>> q = from t in d where t.Key == null select t; // OMG! 
    //vs. 
    var q = from t in d where t.Key == null select t;

    // I simply want the first string, so the last version seems fine.  
    q.First().Key; 

You must use var when there's an anonymous type present because there's no type name to call it by:

var o = new { Num=3, Name="" };

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.

所有深爱都是秘密 2024-08-20 13:55:51

在 ReSharper(8.02,但也可能是其他版本)中,“使用隐式类型局部变量声明”建议的选项可以根据您的偏好进行调整,无论是什么,首先打开选项菜单ReSharper:

ReSharper 选项菜单

然后,在“代码检查”下,调整所选语言的“检查严重性”,在我的case c#:

Turn off隐式类型局部变量建议

如您所见,有一些选项可以调整 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:

ReSharper Options Menu

Then, under "Code Inspection" by adjusting the "Inspection Severity" of your chosen language, in my case c#:

Turn off implicitly typed local variable suggestion

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 :)

九厘米的零° 2024-08-20 13:55:51

'var' 是为了清晰

关于是否使用 var 关键字的主要争论在于代码对您和其他开发人员的可读性如何。

就像你在写一个故事一样,没有明确的正确答案。但让我们用简单的英语来看一些例子。

杰克向比尔打招呼。他不喜欢他,所以转身走了另一条路。

谁走了另一条路?杰克还是比尔?在这种情况下,使用名称“Jake”和“Bill”就像使用类型名称一样。而“He”和“him”就像使用var关键字。在这种情况下,说得更具体可能会有所帮助。下面的例子就更清楚了。

杰克向比尔打招呼。杰克不喜欢比尔,所以他转身走了另一条路。

在这种情况下,更具体可以使句子更清晰。但情况并非总是如此。在某些情况下,具体化会使阅读变得更加困难。

比尔喜欢读书,所以比尔去了图书馆,比尔拿出了一本比尔一直喜欢的书。

在这种情况下,如果我们使用“he”,并且在某些情况下将他的名字全部省略,那么阅读句子会更容易,这相当于使用 var 关键字。

比尔喜欢读书,所以他去图书馆拿出了一本他一直喜欢的书。

这些例子涵盖了要点,但并没有讲述整个故事。在这些例子中,只有一种方式来指代这个人。要么使用他们的名字,要么使用更通用的术语,如“他”和“他”。

就代码而言,我们有 3 种方法来帮助提高清晰度。类型、变量名和赋值。以这行代码为例:

Person p = GetPerson();

现在的问题是,这行代码中是否有足够的信息来帮助您弄清楚发生了什么?

下面这行代码怎么样?您是否仍然知道 p 在这种情况下意味着什么:

var p = GetPerson();

现在怎么样:

var p = Get();

或者现在:

var person = Get();

或者这个:

var t = GetPerson();

或者这个:

var u = Person.Get();

关键字 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.

Jake said hello to Bill. He didn't like him so he turned and went the other way.

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.

Jake said hello to Bill. Jake didn't like Bill so he turned and went the other way.

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.

Bill likes books, so Bill went to the library and Bill took out a book that Bill has always liked.

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.

Bill likes books, so he went to the library and took out a book that he has always liked.

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:

Person p = GetPerson();

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:

var p = GetPerson();

How about now:

var p = Get();

Or now:

var person = Get();

Or this one:

var t = GetPerson();

Or this:

var u = Person.Get();

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.

不醒的梦 2024-08-20 13:55:51

令我惊讶的是,没有人提到更改实例化对象的类型也更容易,因为它

AVeryLongTypeName myVariable = new AVeryLongTypeName( arguments );

是一种重复形式。如果我想将 AVeryLongTypeName 更改为其派生类之一,则在使用 var 时只需更改一次,并且仍然可以访问子类的方法。

除此之外,提高可读性是很重要的一点,但正如其他人所说,var 不应该被过度使用,所以我认为在 Resharper 中关闭提示是绝对可以的。

I am surprised that nobody mentioned that it is also easier to change the type of the instantiated object, because

AVeryLongTypeName myVariable = new AVeryLongTypeName( arguments );

is a form of repetition. If I want to change AVeryLongTypeName into one of its derived classes, I need only change this once when using var 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.

一枫情书 2024-08-20 13:55:51

我也不喜欢这个。

我不希望这变成关于 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

挖鼻大婶 2024-08-20 13:55:51

我看到了很多正确答案,但缺少完整的答案。

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

我曾尝试先对其他帖子发表评论,以添加设置这些帖子的位置,但没有声誉。显然,我也没有资格发布我的设置屏幕截图。

我将解释如何到达那里。

在 Visual Studio 中>主菜单>重磨器>选项>代码编辑> C#>代码风格>声明中的 Var 使用

  • 对于内置类型 使用显式类型
  • 对于简单类型 在明显时使用 'var'
  • 在其他地方使用 '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 when var is used and the type is obvious such as when you use a new statement. I saw one post that showed how to update inspection severity to only show hints for the use of var.

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

  • For built-in types Use explicit type
  • For simple types Use 'var' when evident
  • Elsewhere Use'var'

enter image description here

ReSharper help documentation: Code Syntax Style: Implicit/Explicit Typing ('var' Keyword)
— Configure preferences of using 'var' keyword

天煞孤星 2024-08-20 13:55:51

我的规则是这样的:

  • 你是否声明一个基本类型(即bytecharstringint[]< /code>、双精度?十进制等)? ->使用类型:

    string myStr = "foo";
    int[] myIntArray = [123, 456, 789];
    双倍的? myDouble = 123.3;
    

  • 您是否声明了复杂类型(即 ListDictionaryMyObj) ? ->使用var

    var myList = List();
    var myDictionary = Dictionary<字符串, 字符串>();
    var myObjInstance = new MyObj();
    

My rule is this:

  • Are you declaring a primitive type (i.e. byte, char, string, int[], double?, decimal, etc.)? -> Use the type:

    string myStr = "foo";
    int[] myIntArray = [123, 456, 789];
    double? myDouble = 123.3;
    
  • Are you declaring a complex type (i.e. List<T>, Dictionary<T, T>, MyObj)? -> Use var:

    var myList = List<string>();
    var myDictionary = Dictionary<string, string>();
    var myObjInstance = new MyObj();
    
羁〃客ぐ 2024-08-20 13:55:51

我只想指出 C# 编码约定

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

这可能就是 ReSharper 中默认打开提示的原因。他们还在同一文档的下面提供了一些不会提高可读性的情况。

I'd just like to point that the use of "var" is recommended in the C# Coding Conventions

when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important

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.

禾厶谷欠 2024-08-20 13:55:51

ReSharper 建议使用 var,因为它可以使对象创建更加整洁。

比较这两个例子:

StringBuilder bld = new StringBuilder();

var bld = new StringBuilder();

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

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

ReSharper recommends var because it tends to unclutter object creation.

Compare these two examples:

StringBuilder bld = new StringBuilder();

var bld = new StringBuilder();

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.

咽泪装欢 2024-08-20 13:55:51

瓦尔太棒了!我遇到过许多开发人员,他们的印象是 var 绑定到动态类型,但事实并非如此。它仍然是静态类型,只是由编译器决定。

以下是使用 var 的一些令人惊奇的优点

减少输入 var 更短且更易于阅读,例如

Dictionary> postcodes = new Dictionary>() Yuk.

var postcodes = new Dictionary>() \o/\o/

更具描述性的变量名称 - 很脆弱,但我认为让 var 的流动性在这里发挥作用很重要。由于 var 有点模糊,它确实鼓励使用更具描述性的变量名称,而不是让类型自己说话。

更少的代码更改 - 如果方法调用的返回类型发生更改。您只需更改方法调用,而不是使用它的每个地方。

匿名类型 - 匿名类型是一个非常强大的概念,特别是在 WebApi 等领域 部分资源。没有 var,它们就无法使用。

然而,有时显式声明类型很有用,我发现这在基元或结构中最有用。例如,我个人认为这种语法不是很有用:

for(var i = 0; i < 10; i++) 
{

}

vs

for(int i = 0; i < 10; i++) 
{

}

这完全取决于个人喜好,但使用 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. 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.

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:

for(var i = 0; i < 10; i++) 
{

}

vs

for(int i = 0; i < 10; i++) 
{

}

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.

他不在意 2024-08-20 13:55:51

顺便说一句,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.

时光礼记 2024-08-20 13:55:51

.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.

献世佛 2024-08-20 13:55:51

在我看来,只有在定义变量的值时立即清楚类型是什么时才应使用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 能带来任何增益 code>,但我可以想到一些可能有害的场景:

例如,一次性类型的右侧变量值没有清楚地显示类型。 IDisposable 的处置很容易被忘记

示例:

// 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.

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:

var s = "string value";

It is obvious that s is a string.

I believe it is also appropriate when the variable type name is very complex.

Example:

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>>>();

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:

// 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.
蓝天白云 2024-08-20 13:55:51

没有技术上的区别,如果您使用 var,则类型由编译器隐含。如果您有这样的代码:

var x = 1;

x 隐含为 int 并且不能为其分配其他值。

如果您更改变量的类型,则 var 关键字很有用;然后您只需进行一项更改,而不是两项:

var x = 1; --> var x = "hello";
int x = 1; --> string x = "hello";

There is no technical difference, if you use var, the type is implied by the compiler. If you have a code like this:

var x = 1;

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 x = 1; --> var x = "hello";
int x = 1; --> string x = "hello";
羁〃客ぐ 2024-08-20 13:55:51

var 关键字是在 C# 3.0 中引入的 - 它允许我们忘记显式指定类型。

没有真正的区别

使用MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);

var foo = DB.MyObjects.SingleOrDefault( w => w.Id == 1);

除了纯粹的可读性和更少的错误机会。

这看起来像是一个陈词滥调的例子,但是说下面的内容可能会帮助你理解:

var myInt = 23;

返回一个 int 类型,而

var myInt = "23";

返回一个 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:

var myInt = 23;

returns an int type, whereas

var myInt = "23";

returns a string type.

MSDN reference

就是爱搞怪 2024-08-20 13:55:51

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

但是,使用“var”有其局限性。它阻止了多态性的以下使用,这是纯粹的美

假设一只狗继承了动物; Cat 扩展了 Animal 类层次结构:

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

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

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

相同的代码,其中 x 用“var”声明将无法编译

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”。 :-)

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:

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

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

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

The same code, with x declared with 'var' will not compile.

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){}

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'. :-)

世界等同你 2024-08-20 13:55:51

没有技术差异(正如 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.

错爱 2024-08-20 13:55:51

'var' 向您的代码添加了一种“动态”元素(尽管代码当然仍然是严格类型化的)。我建议不要在类型不清楚的情况下使用它。考虑这个例子:

var bar = GetTheObjectFromDatabase();
bar.DoSomething();

ClassA {
  void DoSomething() {
  //does something
  }
}

ClassB {
  void DoSomething() {
  //does something entirely different
  }
}

如果 GetTheObjectFromDatabase() 的返回类型从类型 A 更改为类型 B,我们不会注意到,因为这两个类都实现了 DoSomething()。然而,现在的代码实际上可能会执行完全不同的操作。

这可能与将不同的内容写入日志一样微妙,因此您可能不会注意到,直到为时已晚。

var 的以下使用应该总是没问题的:

var abc = new Something();

'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:

var bar = GetTheObjectFromDatabase();
bar.DoSomething();

ClassA {
  void DoSomething() {
  //does something
  }
}

ClassB {
  void DoSomething() {
  //does something entirely different
  }
}

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 abc = new Something();
杀手六號 2024-08-20 13:55:51

对于那些不喜欢不断使用“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

enter image description here

静赏你的温柔 2024-08-20 13:55:51

根据 JetBrains(ReSharper 的作者)的说法,他们鼓励默认使用 var。

来自他们的网站

使用 C# 3.0 中引入的隐式类型局部变量(也称为 var 关键字)已变得非常流行,因为它提高了许多场景中的可读性。默认情况下,ReSharper 还鼓励使用 var 关键字,但其使用偏好是可以灵活配置的 - 例如,您可以选择在特定情况或任何地方使用显式类型,ReSharper 将帮助您强制执行您的偏好.

According to JetBrains (the author of ReSharper), they encourage the use of var by default.

From their website:

Using implicitly typed local variables (also known as var keyword) introduced in C# 3.0 has become quite popular as it improves readability in many scenarios. By default, ReSharper also encourages using of var keyword, but preferences of its usage are flexibly configurable — for example, you can opt for using explicit types in specific cases or everywhere and ReSharper will help you enforce your preferences.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文