在声明之前不能使用本地变量的人

问题描述 投票:0回答:2

我正在参加这门学校的演习,在这里我必须填补空白以完成代码。这就是我所拥有的:

using System;

class Program {
  public static void Main() {
    var person;
    person = Tuple.Create("John", "Doe");
    string s = "Hello, "+person.Item1 + ", " + person.Item2;
  }
}

运行时,出现以下错误:源程序错误:

(5,5):错误CS0818:隐式键入的局部变量声明符必须包含初始化程序(6,5):错误CS0841:在声明之前无法使用本地变量``人''(7,26):错误CS0841:在声明之前,不能使用本地变量“人”

这里是我可以编辑的空白。

 using System;

 class Program {   public static void Main() {
     ______ person;
     person = ________________________________
     _______ s = "Hello, "+person._____ + ", " + person.______;   } }
c# variables local
2个回答
0
投票

提到的错误实际上是关于implicit type声明规则的。使用var声明变量时,应始终在右侧添加一些内容,像:

var i = 10; // var is internally converting to `int` by Compiler

因为编译器正在从右侧操作确定var类型,在这种情况下,它将与:

int i = 10;

因此,特别是为了使您的情况成功完成代码编译,请合并行56,如下所示:

var person = Tuple.Create("John", "Doe");
string s = "Hello, " + person.Item1 + ", " + person.Item2;

0
投票

仔细阅读编译器给您的错误:

((5,5):错误CS0818:隐式类型的局部变量声明符必须包含初始化程序]

好的,这就是说,如果您使用隐式类型的局部变量,则需要对其进行初始化。原因是,如果不初始化它,编译器将如何找出类型?

这很好:

var s = "Hello"; //this works because the compiler can figure out s is 
                 //a string because you are initializing it with the
                 //string "Hello".

但这不是:

var s; //this fails because the compiler doesn't know what type s is.
s = "Hello";

现在,您可以避免不使用隐式类型的变量开头;只需使用显式类型的变量。效果很好:

string s; //the compiler doesn't have to figure out anything, 
          //s is a string, period.
s = "Hello";

确定,所以现在我们知道编译器无法确定person是什么。一旦那很清楚,您就必须了解person的声明已失败,因此编译器将完全忽略它,but它会继续尝试尽可能多地理解其余代码。

因此,一旦就编译器而言清楚地知道变量person不存在,那么接下来的两个错误就很有意义了:

(6,5):错误CS0841:声明局部变量'person'之前不能使用(7,26):错误CS0841:在声明局部变量“人”之前不能使用它]

编译器只是在告诉您您正在尝试使用从未声明过的名为person的变量。一次尝试将其初始化:person = Tuple.Create("John", "Doe");,一次尝试对其进行初始化:string s = "Hello, " + person.Item1 + ", " + person.Item2;

修复声明,一切都会正常。

© www.soinside.com 2019 - 2024. All rights reserved.