var vs显式声明 [英] var vs explicit declaration

查看:101
本文介绍了var vs显式声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C#中使用var关键字


您好,
刚搬去工作,我习惯于经常使用 var
在我上一份工作中,我们做了很多TDD并使用了reshaper。



在这项工作中,他们讨厌第三方工具,这里的开发人员说这不是一直使用 var 很好,而且效率不如显式键入有效。



我前段时间认为一样,但是现在我已经习惯了,它使我的代码看起来更整洁。



我读了一些帖子,对于是否像高效与否。
我读到使用 var 会产生相同的IL代码。那么它不应该那么有效吗?我在其他地方读到,即使使用 var 会产生相同的IL代码,它也必须找出它是什么类型。
那么,推论的真正含义是什么?



对于在性能方面是否相同的一些澄清将是非常棒的。

解决方案

就执行时间效率而言,这没有什么区别。实际上,它被完全编译为相同的IL。该变量仍将是静态类型,只是从初始化表达式中推断出类型。



推断是指从其他信息中得出。因此,如果声明为:

  string x = hello; 

变量 x 显式地表示 声明为 string 类型。编译器无需执行任何操作。如果您使用 var

  var x = hello; 

然后,编译器找到要分配的表达式的编译时类型,并使 变量的类型。 x 仍然是代码中其他任何地方的字符串变量。



如果开发人员在工作考虑到 var 的行为是动态的,因此我对他们告诉您的其他信息非常谨慎。您可能要谨慎建议他们在评判新语言功能之前会学到一些更多的知识。



developer 效率方面,这是一个很难判断的问题。我个人使用 var 相当-尤其是在测试中-但不是到处都使用。

Possible Duplicate:
Use of var keyword in C#

Hi, Just moved job and I am used to using var a lot. At my previous job we were doing lots of TDD and using resharper.

In this job they hate third party tools and the developers here say that it is not good to use var all the time and it is not as efficient as explicit typing.

Some time ago I thought the same but now I have gotten so used to it, and it makes my code look neater.

I have read some posts and there seems to be confusion whether it is as efficient or not. I read that using var produces the same IL code. So should it not be as efficient? Somewhere else I read that even though using var produces the same IL code it has to find out what type it is. So what does 'inferred' really mean then?

Some clarification as to whether performance wise they are the same would be fantastic.

解决方案

In terms of execution time efficiency, it makes no difference. It is indeed compiled into exactly the same IL. The variable will still be statically typed, it's just that the type is inferred from the initialization expression.

"Inferred" means "worked out from other information". So if the declaration is:

string x = "hello";

the variable x is explicitly declared to be of type string. The compiler doesn't have to work anything out. If you use var:

var x = "hello";

then the compiler finds the compile-time type of the expression being assigned, and makes that the type of the variable. x is still known to be a string variable everywhere else in the code.

If the developers you're working with think that var behaves dynamically, I would be very cautious about other information they tell you. You might want to discreetly suggest that they learn a bit more about how new language features work before judging them.

In terms of developer efficiency, that's a much harder question to judge. Personally I use var quite a bit - particularly in tests - but not everywhere.

这篇关于var vs显式声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆