即使声明,名称也不存在

Tyl*_*ler -11 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;
 }
Run Code Online (Sandbox Code Playgroud)

错误

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

Saj*_*ran 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;
 }
Run Code Online (Sandbox Code Playgroud)


Joh*_*ner 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;
 }
Run Code Online (Sandbox Code Playgroud)