如何在c#中使用var#{}

0 c# if-statement var while-loop

我如何使用c#over {}中的var,如:

if
{
   var test;
   while
   {
      test = "12345";
      //test is defined
   } 
   var test2 = test;
   //test is undefined
}
Run Code Online (Sandbox Code Playgroud)

我不明白.

Rom*_*och 5

您不能使用var未初始化的变量,因为在这种情况下编译器将不知道实际类型.var是语法糖 - 编译器应该决定使用哪种类型,在IL代码中你会看到真正的类型.

如果你真的想要var你应该使用某种类型的任何值(在你的情况下) - 初始化它string:

if
{
   var test = String.Empty; // initialize it - now compiler knows type
   while
   {
      test = "12345";
      //test is defined
   } 
   var test2 = test;
   //test is undefined
}
Run Code Online (Sandbox Code Playgroud)