不能在 switch 语句之外使用声明的变量
Can't use a declared variable outside of a switch statement
我在 switch 语句外声明了一个变量,然后在 switch 语句内向这些变量添加了内容。之后,我尝试使用语句外的变量,但它无法识别我已经放入变量中的答案。
有什么想法吗?
int hp;
int dmg;
int dfn;
switch (className)
{
case "Warrior":
Adventurer ch1 = new Adventurer(13, 40, 10);
dmg = ch1.damage;
hp = ch1.health;
dfn = ch1.defense;
break;
case "Mage":
Adventurer ch2 = new Adventurer(17, 20, 3);
dmg = ch2.damage;
hp = ch2.health;
dfn = ch2.defense;
break;
case "Druid":
Adventurer ch3 = new Adventurer(10, 30, 4);
dmg = ch3.damage;
hp = ch3.health;
dfn = ch3.defense;
break;
case "Thief":
Adventurer ch4 = new Adventurer(20, 15, 1);
dmg = ch4.damage;
hp = ch4.health;
dfn = ch4.defense;
break;
default:
Console.WriteLine("There doesn't exist a class with that name, please try again:");
className = Console.ReadLine();
break;
}
Console.WriteLine(hp);
我认为您可能会因为“使用未分配的局部变量”而得到 error/warning,因为您还没有初始化它。如果是这种情况,请在 switch
之前为局部变量赋值
int hp = 0;
int dmg = 0;
int dfn = 0;
我在 switch 语句外声明了一个变量,然后在 switch 语句内向这些变量添加了内容。之后,我尝试使用语句外的变量,但它无法识别我已经放入变量中的答案。 有什么想法吗?
int hp;
int dmg;
int dfn;
switch (className)
{
case "Warrior":
Adventurer ch1 = new Adventurer(13, 40, 10);
dmg = ch1.damage;
hp = ch1.health;
dfn = ch1.defense;
break;
case "Mage":
Adventurer ch2 = new Adventurer(17, 20, 3);
dmg = ch2.damage;
hp = ch2.health;
dfn = ch2.defense;
break;
case "Druid":
Adventurer ch3 = new Adventurer(10, 30, 4);
dmg = ch3.damage;
hp = ch3.health;
dfn = ch3.defense;
break;
case "Thief":
Adventurer ch4 = new Adventurer(20, 15, 1);
dmg = ch4.damage;
hp = ch4.health;
dfn = ch4.defense;
break;
default:
Console.WriteLine("There doesn't exist a class with that name, please try again:");
className = Console.ReadLine();
break;
}
Console.WriteLine(hp);
我认为您可能会因为“使用未分配的局部变量”而得到 error/warning,因为您还没有初始化它。如果是这种情况,请在 switch
之前为局部变量赋值int hp = 0;
int dmg = 0;
int dfn = 0;