“var”的目的是什么?
可能的重复:
var 关键字有什么意义?
我不询问它是如何工作的。我不是问它是否会影响性能。我已经知道这些答案了。
我想知道 MS C# 团队最初将其添加到该语言中的动机是什么。你不会在语言中添加无聊的东西。它解决了一个值得注意的问题。那是什么问题?
我见过的“它解决的问题”最接近的例子是使用匿名类型时,如下所示:
var linqResult = from element in SomeCollection s
elect new { element.A, element.B }
这种用法的讽刺之处在于,样式和编码标准指南(例如 Microsoft 提供的)建议编码器避免使用 ' var' 当结果类型不明显时。换句话说,“var”的(大概)预期目的与编码标准指南相冲突。
如果我正在编写编码标准,并试图防止过度使用“var”,我会有点倾向于说“仅在响应匿名类型时才使用“var””。但这又带来了一个完整的问题:将“var”添加到语言中的目的是什么?
Possible Duplicate:
What's the point of the var keyword?
I'm not asking how it works. I am not asking if it affects performance. I already know those answers.
I want to know what inspired the MS C# team to add it to the language in the first place. You don't add frivolous things to a language. There must have been a noteworthy problem it solved. What was/is that problem?
The closest example I've seen to "the problem it solves" is when using anonymous types, like this:
var linqResult = from element in SomeCollection s
elect new { element.A, element.B }
The irony about this usage is that style and coding-standards guides (such as provided by Microsoft) advise the coder to avoid using 'var' when the resulting type is not obvious. In other words, the (presumably) intended purpose of 'var' is in conflict with the coding-standard guidelines.
If I were writing coding-standards, and was trying to prevent overuse of 'var', I'd be somewhat inclined to say "use 'var' only in response to anonymous types." But that brings the question full-circle: what was/is the purpose of having added 'var' to the language?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,var 关键字的创建很大程度上是为了通过启用匿名类型来使 LINQ 更容易
As far as I know the var keyword was made pretty much to make LINQ easierby enabling the use of anonymous types
来自 MSDN:
From MSDN:
匿名类型是最重要的类型,但也减少了方法内的重复:
Anonymous Types was the big one, but also reducing repetition within methods:
完全正确!匿名类型。如果没有
var
并且仍然具有智能感知,那么您到底如何保留对创建的匿名类型的引用?换句话说:当没有
var
时,就我们现在拥有的编译时支持而言,就不会有任何可用的匿名类型。匿名类型会出现太多运行时错误。添加的糖分(过度使用时会变得复杂)是您甚至可以将 var 与非匿名变量一起使用。当然它有效,但这是一个坏习惯。
Exactly! Anonymous types. How in the world would you keep a reference to a created anonymous type if there was no
var
and still have intellisense along with it?In other words: When there was no
var
, there wouldn't be any anonymous types in the usable sense we have now with compile time support. There would be just too many runtime errors with anonymous types.The added sugar (of complexity when overused) is that you can use var with even non-anonymous variables. Sure it works but it's a bad habit.