之前我问了一个关于 为什么我看到这么多示例使用 varkeyword 并得到了答案,虽然它只对匿名类型是必需的,但它仍然用于使编写代码更快"/更容易和只是因为".
Earlier I asked a question about why I see so many examples use the varkeyword and got the answer that while it is only necessary for anonymous types, that it is used nonetheless to make writing code 'quicker'/easier and 'just because'.
按照 这个链接(C# 3.0 - Var 不是Objec") 我看到 var 在 IL 中被编译成正确的类型(你会在文章中途看到它).
Following this link ("C# 3.0 - Var Isn't Objec") I saw that var gets compiled down to the correct type in the IL (you will see it about midway down article).
我的问题是,使用 var 关键字的 IL 代码还使用了多少(如果有),如果使用它,它是否甚至接近对代码的性能具有可衡量的水平无处不在?
My question is how much more, if any, IL code does using the var keyword take, and would it be even close to having a measurable level on the performance of the code if it was used everywhere?
推荐答案var 关键字没有额外的 IL 代码:生成的 IL 对于非匿名类型应该是相同的.如果编译器无法创建该 IL,因为它无法确定您打算使用的类型,您将收到编译器错误.
There's no extra IL code for the var keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.
唯一的技巧是 var 会推断出一个确切的类型,如果您手动设置类型,您可能已经选择了接口或父类型.
The only trick is that var will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.
更多推荐
使用“var"会影响性能吗?
发布评论