【问题标题】:Using same variables in a switch statement [duplicate]在 switch 语句中使用相同的变量 [重复]
【发布时间】:2019-09-02 21:57:18
【问题描述】:

我正在制作一个程序来切换到不同的算法。我很想知道您是否可以在 switch 语句中重用变量。

我已尝试查找并更改为 global 和 final 但似乎没有任何效果

enter code here

switch(nr){

case 1: //For one algorithm
Console.Write("Write your base: ")
double b = convert.ToInt32(Console.Readline())

break;

case 2: //For the second algorithm but with the same name on the variable 
Console.Write("Write your second base: ")
double b = convert.ToInt32(Console.Readline())  <<<<< //ERROR on this line
break;


}

由于情况不同,我没想到也会发生这种情况

结构 System.Double

表示一个双精度浮点数

【问题讨论】:

  • 那么,错误信息是什么?仔细阅读,你已经有了答案。
  • C 派生语言(以及其他语言)具有变量 范围 的概念。在大多数情况下,变量的范围是包含变量声明的一对大括号 ({}) 的范围。您只能在单个范围内声明一次变量(规则更复杂,但这是一个简单的总结)。您两次声明b,因此编译器会抱怨。 @Alejandro 在下面的回答将声明提升到 switch 语句之外,允许 b 被使用两次。请注意,即使您在 switch 中声明了一次 b,它也不会在 switch 之外使用

标签: c# switch-statement


【解决方案1】:

试试这个:

int b;

switch(nr){

case 1: //For one algorithm
    Console.Write("Write your base: ");
    b = Convert.ToInt32(Console.ReadLine());
break;

case 2: //For the second algorithm but with the same name on the variable 
    Console.Write("Write your second base: ");
    b = Convert.ToInt32(Console.ReadLine());  <<<<< //ERROR on this line
break;


}

【讨论】:

  • 对于任何遇到“不能在声明之前使用实例”错误的人,请删除案例中变量的所有实例
猜你喜欢
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多