简体   繁体   English

C# 不识别变量

[英]C# does not recognize a variable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school_project_final
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("who are you...?");
            
            string name = Console.ReadLine();

            Console.WriteLine("how old are you " + name + "?");

            int age;

            try
            {
                age = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.WriteLine("that's... not a number");
                return; 
            }
            finally
            {
                if (System.Convert.ToInt32(age) >= 18)
                {
                    Console.WriteLine("so you're " + age + " years old, good to know");
                }
                else if (System.Convert.ToInt32(age) < 18 && System.Convert.ToInt32(age) > 0)
                {
                    Console.WriteLine("so you're a child, how worthless");
                }

                Console.ReadLine();
            }
        }
    }
}

if (System.Convert.ToInt32(age) >= 18)如果 (System.Convert.ToInt32(age) >= 18)

This line returns an error that the age variable does not exist, but the other lines after it like这一行返回一个错误,指出年龄变量不存在,但它后面的其他行

Console.WriteLine("so you're " + age + " years old, good to know");

and

else if (System.Convert.ToInt32(age) < 18 && 
         System.Convert.ToInt32(age) > 0)

do not return this error, how do I fix this?不要返回此错误,我该如何解决?

finally always runs after try/catch, even if there's an execption That's why compiler doesn't think there's a value for age finally总是在 try/catch 之后运行,即使有一个 execption 这就是为什么编译器认为age没有价值

Add your if/else statements in try block在 try 块中添加 if/else 语句

try
{
    age = Convert.ToInt32(Console.ReadLine());
    
    if (age >= 18) 
    {
        Console.WriteLine("so you're " + age + " years old, good to know");
    } 
    else if (age < 18 && age > 0) 
    {
        Console.WriteLine("so you're a child, how worthless");
    }

    Console.ReadLine();
}
catch (FormatException)
{
     Console.WriteLine("that's... not a number");
     return; 
}

The compiler thinks the age value is not assigned in the finally block because it's scope is evaluated regardless of the try block successfully running.编译器认为age值未在 finally 块中分配,因为无论 try 块是否成功运行,都会评估 scope。 In other words, if you got an exception, the finally block wouldn't have any value of age unless you assigned it to something else in the catch.换句话说,如果您遇到异常,除非您将它分配给 catch 中的其他内容,否则 finally 块将没有任何年龄值。

Your if/else statements should be in the try block你的 if/else 语句应该在 try 块中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM