Why C# Need Integral Types already it has "Var" keyword?
This question already has an answer here:
in no particular order...
var
is only a compiler construct; even var i = 4;
is typed as int
var
, and you can't remove keywords without utterly breaking existing code. int
in place of var! Especially when the type matters and there are bytes, floats, enums, decimals etc that all work with the literal 0
; ie short x = 0; int y = 0; long z = 0;
short x = 0; int y = 0; long z = 0;
- why change only int
to var
there? var
to specify a generic type parameter ( <T>
) or in a typeof
var.TryParse
in place of int.TryParse
Many people would argue that it is better practice to write int i = 5
rather than var i = 5
. There are many reasons for this, but the most compelling to me is that I can look at the code and know immediately, without stretching my brain, what type i
is. This allows my brain to concentrate on the harder problems.
In fact var
was introduced to declare variables whose types could not easily be named. It was not introduced as a convenience, although it can be used that way.
The var
keyword is just syntactic sugar, which can only be used for local variables in methods. It's still a strongly typed variable. You can hover the mouse over it in visual studio to see what type it is.
We still need types as otherwise how would you do var list = new List<int>();
? You need to type List<int>
somewhere!
In many cases its best to be explicit, for example when working with literals that could be a number of different types, or to increase readability.
链接地址: http://www.djcxy.com/p/53810.html上一篇: .net 3.5中var数据类型的优缺点