即使声明,名称也不存在

时间:2015-03-22 13:58:49

标签: c#

我的代码

static int IntCheck(string num)
{
    int value;
    if (!int.TryParse(num, out value))
    {
        Console.WriteLine("I am sorry, I thought I said integer, let me check...");
        Console.WriteLine("Checking...");
        System.Threading.Thread.Sleep(3000);
        Console.WriteLine("Yup, I did, please try that again, this time with an integer");
        int NewValue = IntCheck(Console.ReadLine());
    }
    else
    {
        int NewValue = value;
    }
    return NewValue;
 }

错误

  

名称' NewValue'在当前上下文中不存在(第33行)

2 个答案:

答案 0 :(得分:6)

您需要在

之外声明
static int IntCheck(string num)
{
    int value;
    int NewValue;
    if (!int.TryParse(num, out value))
    {
        Console.WriteLine("I am sorry, I thought I said integer, let me check...");
        Console.WriteLine("Checking...");
        System.Threading.Thread.Sleep(3000);
        Console.WriteLine("Yup, I did, please try that again, this time with an integer");
        NewValue = IntCheck(Console.ReadLine());
    }
    else
    {
        NewValue = value;
    }
    return NewValue;
 }

答案 1 :(得分:6)

NewValue的范围是ifelse块。您需要在块外移动声明。

static int IntCheck(string num)
{
    int value;
    int NewValue;
    if (!int.TryParse(num, out value))
    {
        Console.WriteLine("I am sorry, I thought I said integer, let me check...");
        Console.WriteLine("Checking...");
        System.Threading.Thread.Sleep(3000);
        Console.WriteLine("Yup, I did, please try that again, this time with an integer");
        NewValue = IntCheck(Console.ReadLine());
    }
    else
    {
        NewValue = value;
    }
    return NewValue;
 }
相关问题