我应该*总是*支持 C# 3.0 中隐式类型的局部变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-01 08:57:07  来源:igfitidea点击:

Should I *always* favour implictly typed local variables in C# 3.0?

提问by serg10

Resharpercertainly thinks so, and out of the box it will nag you to convert

Resharper肯定是这么认为的,而且开箱即用,它会催促您进行转换

Dooberry dooberry = new Dooberry();

to

var dooberry = new Dooberry();

Is that really considered the best style?

这真的被认为是最好的风格吗?

采纳答案by Jon Galloway

It's of course a matter of style, but I agree with Dare: C# 3.0 Implicit Type Declarations: To var or not to var?. I think using var instead of an explicit type makes your code less readable.In the following code:

这当然是一个风格问题,但我同意敢于:C# 3.0 隐式类型声明:对 var 还是不对 var?. 我认为使用 var 而不是显式类型会使您的代码可读性降低。在以下代码中:

var result = GetUserID();

What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.

结果是什么?一个整数,一个字符串,一个 GUID?是的,这很重要,不,我不应该深入研究代码才能知道。在代码示例中尤其烦人。

Jeff wrote a post on this, saying he favors var. But that guy's crazy!

Jeff 写了一篇关于这个的帖子,说他喜欢 var。但那家伙疯了!

I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.

我看到了 stackoverflow 成功的一种模式:挖掘旧的 CodingHorror 帖子并(危险风格)根据问题来表达它们。

回答by John Sheehan

I have a feeling this will be one of the most popular questions asked over time on Stack Overflow. It boils down to preference. Whatever you think is more readable. I prefer var when the type is defined on the right side because it is more terse. When I'm assigning a variable from a method call, I use the explicit type declaration.

我有一种感觉,随着时间的推移,这将成为 Stack Overflow 上最受欢迎的问题之一。它归结为偏好。无论您认为什么都更具可读性。当类型在右侧定义时,我更喜欢 var ,因为它更简洁。当我从方法调用分配变量时,我使用显式类型声明。

回答by OJ.

"Best style" is subjective and varies depending on context.

“最佳风格”是主观的,因上下文而异。

Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.

有时,使用 'var' 比输入一些非常长的类名要容易得多,或者如果您不确定给定函数的返回类型。我发现在处理 Linq 或 for 循环声明时,我更多地使用了“var”。

Other times, using the full class name is more helpful as it documents the code better than 'var' does.

其他时候,使用完整的类名更有帮助,因为它比“var”更好地记录代码。

I feel that it's up to the developer to make the decision. There is no silver bullet. No "one true way".

我觉得应该由开发商来做出决定。没有银弹。没有“一种真正的方式”。

Cheers!

干杯!

回答by Mark Cidade

No not alwaysbut I would go as far as to say a lot of the time. Type declarations aren't much more useful than hungarian notation ever was. You still have the same problem that types are subject to change and as much as refactoring tools are helpful for that it's not ideal compared to not having to change where a type is specified except in a single place, which follows the Don't Repeat Yourself principle.

不,并非总是如此,但我会说很多时候。类型声明并不比匈牙利符号有用得多。您仍然遇到相同的问题,即类型可能会发生变化,并且重构工具对这一点很有帮助,与不必更改指定类型的位置相比,除了在一个地方(遵循不要重复自己)相比,它并不理想原则。

Any single line statement where a type's name can be specified for both a variable and its value should definitely use var, especially when it's a long Generic< OtherGeneric< T,U,V>, Dictionary< X, Y>>>

任何可以为变量及其值指定类型名称的单行语句都应该使用 var,尤其是当它是一个很长的 Generic<OtherGeneric<T,U,V>,Dictionary<X,Y>>>

回答by Ryan Sampson

There was a good discussion on this @ Coding Horror

对此@Coding Horror进行了很好的讨论

Personally I try to keep its use to a minimum, I have found it hurts readability especially when assigning a variable from a method call.

就我个人而言,我尽量减少它的使用,我发现它会损害可读性,尤其是在从方法调用中分配变量时。

回答by Darren Kopp

@jongalloway - var doesn't necessarily make your code more unreadable.

@jongalloway - var 不一定会使您的代码更不可读。

var myvariable = DateTime.Now
DateTime myvariable = DateTime.Now;

The first is just as readable as the second, and requires less work

第一个和第二个一样可读,并且需要更少的工作

var myvariable = ResultFromMethod();

here, you have a point, var could make the code less readable. I like var because if i change a decimal to a double, i don't have to go change it in a bunch of places (and don't say refactor, sometimes i forget, just let me var!)

在这里,您有一个观点,var 可能会使代码的可读性降低。我喜欢 var 因为如果我将小数更改为双精度,我不必在很多地方更改它(不要说重构,有时我忘记了,让我变吧!)

EDIT:just read article, i agree. lol.

编辑:只是阅读文章,我同意。哈哈。

回答by John Richardson

One of the advantages of a tool like ReSharper is that you can write the code however you like and have it reformat to something more maintainable afterwards. I have R# set to always reformat such that the actual type in use is visible, however, when writing code I nearly always type 'var'.

像 ReSharper 这样的工具的优势之一是您可以随心所欲地编写代码,然后将其重新格式化为更易于维护的内容。我将 R# 设置为始终重新格式化,以便可以看到实际使用的类型,但是,在编写代码时,我几乎总是键入“var”。

Good tools let you have the best of both worlds.

好的工具让您两全其美。

John.

约翰。

回答by lomaxx

There's a really good MSDN articleon this topic an it outlines some cases where you can't use var:

有一个真正的好MSDN文章关于这个主题的它概括某些情况下,你不能使用VAR:

The following restrictions apply to implicitly-typed variable declarations:

以下限制适用于隐式类型变量声明:

  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.
  • var 只能在同一个语句中声明和初始化局部变量时使用;该变量不能初始化为 null,也不能初始化为方法组或匿名函数。
  • var 不能用于类范围内的字段。
  • 使用 var 声明的变量不能在初始化表达式中使用。换句话说,这个表达式是合法的:int i = (i = 20); 但是这个表达式会产生一个编译时错误:var i = (i = 20);
  • 不能在同一个语句中初始化多个隐式类型变量。
  • 如果名为 var 的类型在范围内,则 var 关键字将解析为该类型名称,并且不会被视为隐式类型局部变量声明的一部分。

I would recommend checking it out to understand the full implications of using var in your code.

我建议查看它以了解在代码中使用 var 的全部含义。

回答by sieben

I use it only when it's clearly obvious what var is.

我只在很明显 var 是什么时才使用它。

clear to me:

对我来说很清楚:

XmlNodeList itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];

not clear to me:

我不清楚:

var itemList = rssNode.SelectNodes("item");
var rssItems = new RssItem[itemList.Count];

回答by serg10

I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.

我看到了 stackoverflow 成功的一种模式:挖掘旧的 CodingHorror 帖子并(危险风格)根据问题来表达它们。

I plead innocent! But you're right, this seemed to be a relatively popular little question.

我辩解无罪!但你是对的,这似乎是一个相对流行的小问题。