What is the purpose of '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?


匿名类型是最大的,但也减少了方法中的重复:

Dictionary<MyCustomType, List<MyOtherCustomType>> dict = new Dictionary<MyCustomType, List<MyOtherCustomType>>();

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.


据我所知,var关键字几乎可以让LINQ更容易使用匿名类型

链接地址: http://www.djcxy.com/p/53826.html

上一篇: 是什么 ”??” 运营商的?

下一篇: 'var'的目的是什么?