What advantages does using var have over the explicit type in C#?
Possible Duplicates:
What's the point of the var keyword?
Use of var keyword in C#
I understand how IEnumerable<...>
for a datatype can make the code a little less readable or how nested generics can seem a little daunting. But aside from code readability, are there advantages to using var instead of the explicit type? It seems like by using the explicit type, you'd better convey what the variable is capable of because you know what it is.
If it's a workplace coding standard, I use it for the sake of teamwork. In my own projects however, I prefer to avoid the user of var.
The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists. All other uses I consider to be lazy coding.
Using var
as the iterator variable for a foreach block is more type safe than explicit type names. For example
class Item {
public string Name;
}
foreach ( Item x in col ) {
Console.WriteLine(x.Name);
}
This code could compile without warnings and still cause a runtime casting error. This is because the foreach loop works with both IEnumerable
and IEnumerable<T>
. The former returns values typed as object
and the C# compiler just does the casting to Item
under the hood for you. Hence it's unsafe and can lead to runtime errors because an IEnumerable
can contain objects of any type.
On the other hand the following code will only do one of the following
x
is typed to object
or another type which does not have a Name field / property The type of 'x' will be object
in the case of IEnumerable
and T
in the case of IEnumerable<T>
. No casting is done by the compiler.
foreach ( var x in col ) {
Console.WriteLine(x.Name);
}
I like it, especially in unit tests, because as the code evolves I only have to fix up the right-hand side of the declaration/assignment. Obviously I also have to update to reflect the changes in usage, but at the point of declaration I only have to make one change.
链接地址: http://www.djcxy.com/p/53804.html上一篇: var vs显式声明
下一篇: 使用var对C#中显式类型有什么优势?