C# 即使已声明,名称也不存在

C# 即使已声明,名称也不存在,c#,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.

我的代码

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行)


你需要在外面申报

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;
 }

NewValue在
if
else
块内的范围内。您需要将声明移到块之外

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;
 }

定义方法顶部的
NewValue
。由于
NewValue
的两个定义都位于
if
else
块的内部,因此无法从外部访问它们。旁注:在询问编译器错误之前,最好先检查MSDN对此的说明,即在这种情况下:如果在循环或
try
if
块中声明变量,然后试图从封闭的代码块或单独的代码块访问它,则经常发生此错误