C#"发现"返回类型功能

Gui*_*ngo 2 .net c# var

在c#中,当返回一个值时,指定变量类型是不必要的.例如:

foreach(var variable in variables) {
}
Run Code Online (Sandbox Code Playgroud)

我正在构建一个企业软件,今天它是一个小型解决方案,但它会变得很大.这种语言功能可能会降低性能,因为我们在应用程序中反复使用它?

我还没有找到如何调用此功能,我想知道更多关于它的信息,如何调用它?

Sim*_*ead 13

var用于implicitly typing变量.

它发生在编译时.没有性能问题.

例子:

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)

  • 嗯,小心点..NET中有很多集合类型,旧的,其中foreach循环中的变量被推断为*object*类型.尽早取消装箱肯定会有所作为. (2认同)

Son*_*nül 5

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关键字也有一些限制.你无法分配varnull.您也不能将其var用作参数类型或方法的返回值.

退房MSDN.