变量初始化差异

本文关键字:初始化 变量 | 更新日期: 2023-09-27 18:29:42

有很多方法可以初始化变量,例如string varName;等等。但是var appWindow = new AppWindow();AppWindow appWindow = new AppWindow(); 之间有什么不同

它们是一样的吗?

有人能解释一下原因吗,因为我是c#的外国人。

感谢

变量初始化差异

这两个代码是等效的,并且两者的IL代码是相同的。这里有一个示例来证明两者的IL代码是相似的:

private static void mycompareMethod()
{
    var str1 = new String(new char[10]);
    string str2 = new String(new char[10]);
}

IL输出:

{
  .method private hidebysig static void  mycompareMethod() cil managed
  .maxstack  2
  .locals init ([0] string str1,
           [1] string str2)
  IL_0000:  nop
  IL_0001:  ldc.i4.s   9
  IL_0003:  newarr     [mscorlib]System.Char
  IL_0008:  newobj     instance void [mscorlib]System.String::.ctor(char[])
  IL_000d:  stloc.0
  IL_000e:  ldc.i4.s   9
  IL_0010:  newarr     [mscorlib]System.Char
  IL_0015:  newobj     instance void [mscorlib]System.String::.ctor(char[])
  IL_001a:  stloc.1
  IL_001b:  ret
} // end of method Program::mycompareMethod

它是相同的,但不能同时使用两者。var appWindow = new AppWindow();在类型明显时使用的第一个,并立即初始化您的变量。

AppWindow appWindow; //using var you will get compile error
if(true)
 appWindow = _GetFromAnotherMethod();
else
 appWindow = new AppWindow();