C# 在if/else中创建int并在以后使用

C# 在if/else中创建int并在以后使用,c#,if-statement,scope,C#,If Statement,Scope,我在这里玩东西,有点麻烦 我有一个输入;它可以是数字或字母。我得看看是数字还是字母。所以我用了一个if。如果输入是一个数字,我的代码应该创建一个int。如果它是一个字母,它应该创建一个不同的int。但是由于某种原因,我以后不能使用整数。有办法解决吗 Console.WriteLine("Length (ms)"); string I = Console.ReadLine(); int I2 = Int32.Parse(I); Console.WriteLine("Height: r for ra

我在这里玩东西,有点麻烦

我有一个输入;它可以是数字或字母。我得看看是数字还是字母。所以我用了一个
if
。如果输入是一个数字,我的代码应该创建一个int。如果它是一个字母,它应该创建一个不同的int。但是由于某种原因,我以后不能使用整数。有办法解决吗

Console.WriteLine("Length (ms)");
string I = Console.ReadLine();
int I2 = Int32.Parse(I);
Console.WriteLine("Height: r for random");
string L = Console.ReadLine();
//So it asks for an input,for which I here want to check what it is
if (L != "r")
{
    int He = Int32.Parse(L);
}
else
{
    Random Hi = new Random();
    int He = Hi.Next(1, 50);
}
//----------------------I want to use the ints in here
while(true)
{
    Random R = new Random();
    Random R2 = new Random();
    int H = R2.Next(1,He);
    int rH = H * 100;
    Console.WriteLine("Height is {0}",H);
    Console.Beep(rH,I2);

您需要调整
int的范围,使其超出条件块

int He;
if (L != "r")
{
     He = Int32.Parse(L);
}
else
{
     Random Hi = new Random();
     He = Hi.Next(1, 50);
}
您还可以在本例中使用,以使代码看起来更像风格上更可取的代码

int He = L != "r" ? Int32.Parse(L) : (new Random()).Next(1, 50);

关于上述两个版本,值得注意的一点是,
Int32.Parse
可能会根据
字符串L
的格式引发许多异常,您可能希望使用语句或方法来处理这些异常

在前面的范围中定义它然后在语句内部赋值。在此问题上要搜索的关键字是“范围”。声明参数的作用域基本上是在其中声明的最内层块。可能的重复项