隐式类型变量是未来的发展方向吗 (C#)
我在最初为 .net v2 编写的项目中使用 StyleCop for Resharper。但我已经将这个项目升级为 3.5 框架。
Stylecop 建议我将大部分显式类型变量更改为隐式类型,例如:
string - var
自定义强类型 - var
这是使用 .net 3.5 项目时的前进方向。将所有内容都声明为 var 似乎很不寻常。
如果我的术语用完了,请随时更新问题标题......
I am using StyleCop for Resharper on a project originally written for .net v2. But I've since upgraded this project for 3.5 framework.
Stylecop is recommending I change the bulk of my explicitly typed variables to implicitly typed for example:
string - var
custom strong type - var
Is this the way forward when working with a .net 3.5 project. It seems unusual declaring everything as var.
Feel free to update the question title if my terminology is out...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这些不是泛型,而是隐式类型变量。这实际上很大程度上是一个品味问题。有些地方可能会过度使用
var
并且有些地方非常明显有必要(想想匿名类型),因此只需在中间找到适合您(和您的团队)偏好的地方即可。Those are not generics, those are implicitly typed variables. This is really largely a matter of taste. There are places where you can overdo the use of
var
and there are places where it's very clearly necessary (think anonymous types) so just find the place in the middle that suits your (and your team's) preference.在很多地方都引起了争论,这取决于品味。比较这两行代码:
你更喜欢哪一行?
Been debated in many places, and it's down to taste. Compare these two lines of code:
Which do you prefer?
看看这个
var(C# 参考) 和
隐式类型局部变量(C# 编程指南)
另请参阅 在 C# 中使用 var 关键字
和 C# 辩论:什么时候应该使用 var?
Have a look at this
var (C# Reference) and
Implicitly Typed Local Variables (C# Programming Guide)
Also have a look at Use of var keyword in C#
and C# Debate: When Should You Use var?
我认为这更多的是一个建议,应该考虑,但不一定完全实施。
虽然我个人认为 var 的最佳用途是当声明/返回类型显而易见时,即:
与
另外,我真的很喜欢能够用更少的代码声明泛型类型:
与
I believe its more of a suggestion and should be considered, but not necessarily implemented fully.
While personal I believe the best use of var is when the declaring/returning type is obvious, i.e:
versus
Also I really enjoy being able to declare generic types with less code:
versus
当使用例如匿名类型时,var 非常重要...
Resharper 会建议全部更改为 var。对于像
我这样明显的定义,我喜欢使用它。
对于某些 API 调用,我可能会明确写下类型:
var is quite important when using e.g. anonymous types...
Resharper will suggest to change all to var. For obvious definitions like
I like to use it.
for some API call I may write down the type explicitly: