哪一个更好? “var”或“数据类型”?

发布于 2024-09-26 12:47:38 字数 281 浏览 1 评论 0 原文

哪一个声明变量更好或者更快?

var ds = new Class1();

或者

Class1 ds = new Class1();

我自己认为第二个应该更快,因为编译器不需要查找类型 Class1,但一些插件如 ReSharper 总是通知我更改 Class1var
谁能解释一下为什么?

which one is better or maybe faster for declaring a variable?

var ds = new Class1();

OR

Class1 ds = new Class1();

I myself believe that second one should be faster coz compiler doesn't need to look for the type Class1, but some addins like ReSharper always notify me to change Class1 to var.
Can anyone explain me why?

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

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

发布评论

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

评论(6

长伴 2024-10-03 12:47:38

它们编译为相同的 IL,因此两者都不会更快。然而,可读性可能存在很大差异。

倾向于倾向于显式声明变量的类型,但如果以下任何情况适用,请使用var

  • 我正在调用构造函数并且类型名称很长(特别是对于泛型)
  • 我使用匿名类型
  • 类型名称很长并且初始化表达式很长,但仍然非常清楚它将返回
  • 我想要的 类型强调代码的目的,而不是它如何实现其结果

与许多可读性问题一样,关于在哪里使用 var 有各种各样的意见 - 从“无处”到“无处不在”。请注意,您可以更改 ReSharper 在选项中为您推荐的内容。 (我似乎记得默认情况下它“建议”双向 - 所以实际上它只是让您更容易切换。)

几个答案提到了所涉及的击键次数。我认为这是支持 var最坏可能原因。我很少(如果有的话)在打字速度上遇到瓶颈。我的编码速度在很大程度上取决于我对问题领域的理解,以及我对解决方案的想象有多清晰。我宁愿输入 2000 次击键,但最终得到一个优雅的设计,实际上用 100 个字符来表示,而不是仅仅键入 500 次击键来获得可读性较差的 500 个字符的设计。想想花在阅读代码上的时间而不是打字的时间。

They compile to the same IL, so neither will be faster. However, there can be a big difference in readability.

I tend to favour explicitly declaring the type of the variable, but use var if any of the following cases applies:

  • I'm calling a constructor and the type name is long (particularly with generics)
  • I'm using anonymous types
  • The type name is reasonably long and the initialization expression is long, but still very clear as to what type it will return
  • I want to emphasize the purpose of the code instead of how it achieves its result

As with many issues of readability, there's a vast range of opinions about where to use var - from "nowhere" to "everywhere". Note that you can change what ReSharper recommends for you in the options. (I seem to remember that by default it "recommends" both ways round - so really it's just making it easier for you to switch.)

A couple of answers have mentioned the number of keystrokes involved. I think this is the worst possible reason to favour var. I'm rarely, if ever, bottlenecked on typing speed. My coding speed is far more heavily dependent on my understanding of the problem domain, and on how clearly I can imagine the solution. I would far rather enter 2000 keystrokes but end up with an elegant design which is actually represented in 100 characters than type a mere 500 keystrokes for a less-readable 500-character design. Think about the time spent reading the code rather than the mechanics of typing.

难以启齿的温柔 2024-10-03 12:47:38

它们都编译成相同的东西。使用 var 时,您只需让编译器在编译时推断类型即可。这可能会增加一点编译时间(我没有实际测试过该部分),但对运行时不会产生影响。

前者的优点(这是我个人更喜欢的)是当你开始处理长类型名称时:

var conn = new System.Data.SqlConnection(connString);

比以下方式更少的击键并且更容易阅读:

System.Data.SqlConnection conn = new System.data.SqlConnection(connString);

此外,没有 var,使用 Anonymous类型几乎是不可能的:

var someObj = new { Name = "Test", Saying = "Hello World!" };

尽管有时我更喜欢使用完整的类型名称而不是 var 。其中最值得注意的是处理方法的返回值时。如果从方法名称中不清楚返回值的类型是什么,我将明确定义它。如果将来发生任何变化,这可以减少混乱。

They both compile to the same thing. When using var, you're simply letting the compiler infer the type at compile time. That may add a little bit of time to compilation (I haven't actually tested that part), but will have no impact at run-time.

The advantage of the former (which is what I prefer personally) is when you start to deal with long Type names:

var conn = new System.Data.SqlConnection(connString);

Is a lot less keystrokes and easier to read than:

System.Data.SqlConnection conn = new System.data.SqlConnection(connString);

In addition, without var, using Anonymous Types would be nearly impossible:

var someObj = new { Name = "Test", Saying = "Hello World!" };

There are definitely times that I prefer to use the full type name instead of var though. The most notable of which is when handling a return value of a method. If it is not clear from the name of the method what the type of the return value to be, I will explicitly define it. That reduces confusion in case anything changes down the road.

喜爱皱眉﹌ 2024-10-03 12:47:38

这只是编译时的类型推断,因此没有性能成本。 “性能增益”是编写 var 的速度更快:)

This is merely type inference at compile time, so there is no performance cost. The "performance gain" is that it is faster to write var :)

失与倦" 2024-10-03 12:47:38

一般来说,当没有必要(匿名类型)并且类型名称不是非常复杂(Dictionary>> 等)。

每次我听到这个建议时,查看 ReSharper 都会在我的待办事项列表中进一步滑动。

As a rule I would favour leaning against var when it isn't necessary (it is with anonymous types) and the type name isn't horribly complicated (Dictionary<int, List<Class.InnerClass<HashSet<SomeOtherClass>>> or such).

Every time I hear about this suggestion, checking out ReSharper slides a bit further down my to-do list.

暗藏城府 2024-10-03 12:47:38

没有性能差异——var 的类型是在编译时确定的。

至于哪个更好,这是一个偏好问题。就我个人而言,如果代码清楚地标识了 var 的类型,我更喜欢 var。示例:


// very much preferred
var o = new System.blah.blah.Class1()

但是,如果您必须过多考虑类型,那么就像类型 def:


  // I don't like this much because the return type isn't obvious
  var result = AMethodThatReturnsSomeKindOfValue()

There is no performance difference -- the type of var is determined at compile time.

As to which one is better, it's a matter of preference. Personally, I prefer var if the code clearly identifies the type of var. Example:


// very much preferred
var o = new System.blah.blah.Class1()

However, if you have to think too much about the type, then like the type def:


  // I don't like this much because the return type isn't obvious
  var result = AMethodThatReturnsSomeKindOfValue()

笑梦风尘 2024-10-03 12:47:38

选择更具可读性的内容。在您的示例中,我认为第一个示例更具可读性并且重复较少。如果您没有在同一行上有类名(例如,因为您将变量初始化为方法调用的结果),那么我将使用类型名称声明样式使其对正在阅读代码的任何人都明确显示。

Go with whatever is more readable. In your example, I think that the first example is more readable and has less duplication. If you don't have the class name on the same line (because you are initializing the variable to the result of a method call for example), then I would use the type name declaration style to make it explicit to whoever is reading the code.

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