在c#中,当返回一个值时,指定变量类型是不必要的.例如:
foreach(var variable in variables) {
}
Run Code Online (Sandbox Code Playgroud)
我正在构建一个企业软件,今天它是一个小型解决方案,但它会变得很大.这种语言功能可能会降低性能,因为我们在应用程序中反复使用它?
我还没有找到如何调用此功能,我想知道更多关于它的信息,如何调用它?
Sim*_*ead 13
var用于implicitly typing变量.
它发生在编译时.没有性能问题.
var例子:
var i = 12; // This will be compiled as an integer
var s = "Implicitly typed!"; // This will be compiled as a string
var l = new List<string>(); // This will be compiled as a List of strings
Run Code Online (Sandbox Code Playgroud)
Var是一个implicit type.它使用C#编程语言中的任何类型别名.别名类型由C#编译器确定.这没有性能损失.该var关键字具有相同的性能.它不会影响运行时行为.
var i = 5; // i is compiled as an int
var i = "5" ; // i is compiled as a string
var i = new[] { 0, 1, 2 }; // i is compiled as an int[]
var i = new[] { "0", "1", "2" }; // i is compiled as an string[]
var i = new { Name = "Soner", Age = 24 }; // i is compiled as an anonymous type
var i = new List<int>(); // i is compiled as List<int>
Run Code Online (Sandbox Code Playgroud)
var关键字也有一些限制.你无法分配var到null.您也不能将其var用作参数类型或方法的返回值.
退房MSDN.