C#中try块外的变量范围

use*_*906 -1 c# scope

我对 C# 很陌生,并且对变量范围感到困惑。这是我编写的代码块,但是当我尝试在 try 块之外访问 a 和 b 的值时,它给了我编译时错误

class TestConditionalStatements
{
    static void Main(string[] args)
    {
        int a, b;
        try
        {
            a = 10;
            b = 20;

        }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }
        //This line gives compile time error
        ConditionalStatements c = new ConditionalStatements(a, b);
        string result;
        c.checkValidity(c, out result);
        Console.WriteLine(result);


    }
}
Run Code Online (Sandbox Code Playgroud)

Ver*_*dus 5

变量 a 和 b 可能不会在该行初始化。假设在线抛出异常:

a = 10;
Run Code Online (Sandbox Code Playgroud)

那么b的值是多少?您需要在 try catch 之前用一个值初始化 a 和 b:

int a = 0, b = 0;
try
{
    a = 10;
    b = 20;
}
catch (Exception e)
{
    Console.Write(e.Message);
}
Run Code Online (Sandbox Code Playgroud)

或者在 catch 子句中给它们一个值:

int a , b ;
try
{
    a = 10;
    b = 20;
}
catch (Exception e) {
    a = 0;
    b = 0;
    Console.Write(e.Message);
}
Run Code Online (Sandbox Code Playgroud)