为什么使用var作为变量类型
可能的重复:
C# 中 var 关键字的使用
我真的不明白为什么你会C# 中的 var
关键字
此代码:
var s = "my string";
与:
string s = "my string";
相同您想让编译器确定要使用的最佳类型吗?当然您应该知道要使用什么类型。毕竟你是在写代码吗?
写第二段代码不是更清晰/干净吗?
Possible Duplicate:
Use of var keyword in C#
I don't really understand why you would the var
keyword in C#
This code:
var s = "my string";
is the same as:
string s = "my string";
Why would you want to let the compiler determine the best type to use. Surely you should know what type to use. After all you are writing the code?
Isn't it clearer/cleaner to write the second piece code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅在 C# 中使用 var 关键字
它非常非常主观!
就我个人而言,当我认为类型很明显并且我想从源代码中删除“噪音”时,我会使用“var”。
See Use of var keyword in C#
Its very, very subjective!
Personally, I use "var" when I think its obvious what the type is, and I want to remove "noise" from the source code.
对我来说在那里使用它也没有多大意义。对于某些人来说,我可以看到更多的一点只是为了节省打字:
但即便如此,我也不想这样做,因为智能感知无论如何都会节省大部分打字。不过,对于 Linq,我几乎总是使用它 - 你可以确定类型,但如果你更改语句,这可能会改变,所以有点麻烦。
It doesn't make much sense to me to use it there either. For some I can see more of a point just to save typing:
But even then I'd be tempted not to, as intellisense saves most of the typing anyway. For Linq, though, I pretty much always use it - you can determine the type, but this might change if you change the statement so it's a bit of a hassle.
变成
或匿名类型,ala LINQ:
我曾经更频繁地使用它,但现在我尝试避免使用它,例如:
对于这个例子,尽管如此,如果您尝试使用另一个解决方案中的代码,它仍然很有用您知道将要重构,但您仍然必须编写代码。
becomes
Or anonymous types, ala LINQ:
I used to use it more often, but now I try to avoid it for stuff like:
For this example, though, it can still be useful if you're trying to work against code from another solution that you know is going to be refactored, but you still have to write code against.
使用它是因为 var 比 string 短,并且如果您有一个表达式(尤其是泛型表达式),其中类型很长并且不需要键入。事实上,使用 var 几乎没有任何缺点,因为 VS 会在鼠标悬停在变量名称上时弹出类型。
You use it because var is shorter than string and if you have an expression (especially a generic one) where the type is lengthy and unnecessary to type. The reality is that there's virtually no downside to using var as VS will pop up the type on mouseover of a variable name.
节省输入并删除不必要的代码,但仅当您声明的类型显而易见时才使用它
To save typing and remove unnecessary codes, but use it only when it is obvious what type you are declaring