C#“发现”返回类型功能

时间:2013-01-27 10:37:29

标签: c# .net var

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

foreach(var variable in variables) {
}

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

我还没有找到如何调用此功能,我想了解更多信息,如何调用它?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:5)

Varimplicit 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>

var关键字也有一些限制。您无法将var分配给null。您也不能将var用作方法的参数类型返回值

MSDN退房。

答案 2 :(得分:2)

如上所述varimplicit type,编译器会在compile-time var类型ildasm.exe处运行。没有性能问题。您可以编写一些测试代码,编译并使用CIL来检查生成的> public int ReturnValue() { > var a = 5; > int b = 5; > > return a + b; }

MSDN - View Assembly Contents


<强> Example

  

注意:int声明与IL中的var声明相同。所以执行引擎不知道你使用了var。

     

并且:它们编译为同一个IL。 var关键字与int或string等显式类型一样快。

     

使用var [C#]

的中间语言方法
.method public hidebysig instance int32  ReturnValue() cil managed
{
  // Code size       9 (0x9)
  .maxstack  1
  .locals init ([0] int32 result,
       [1] int32 CS$1$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.5
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  stloc.1
  IL_0005:  br.s       IL_0007
  IL_0007:  ldloc.1
  IL_0008:  ret
} // end of method VarKW::ReturnValue
  

IL的方法

{{1}}