in the c# var
C# 3.0 introduced
var
var
Improper use
Using var
will reduce the readability and maintenance of the code in the following circumstances, increase the potential errors:
var
The reasonable use of
foreach (var item in someList) { // 'item' 的类型不明确 // ... } var something = someObject.SomeProperty; // 'something' 的类型不明确 var something = someMethod(); // 'something' 的类型不明确
In the following circumstances, using can improve the readability of the code without affecting type security: var
var
var l = new List<string>(); // `l` 的类型一目了然 var s = new SomeClass(); // `s` 的类型一目了然
in the Linq query is more subtle:
var
Although the compiler can infer the type of
var
var results = from r in dataContext.SomeTable select r; // `results` 的具体类型并非完全清晰
results
Using
var
This is similar to <似>, and there are hidden dangers of types of security. When calling the heavy load method, it is easy to pass in the type of non -matching type, resulting in runtime errors.
<<> and type security var
var results = from item in someList where item != 3 select item;
foreach (var item in someList)
Conclusion
Keywords can improve the readability and simplicity of the code under appropriate circumstances, but it needs to be used with caution. When the type is not clear, the risk may be increased, and the use of var
should be avoided. For Linq queries and Linq To Objects, the importance of weighing readability and type security needs to be weighing. Use to make the code clearer and more concise, while maintaining the robustness and maintenance of the program.
The above is the detailed content of When Should You—and Shouldn't You—Use `var` for Type Inference in C#?. For more information, please follow other related articles on the PHP Chinese website!