抛出异常而不设置参数时的行为是什么?

Sop*_*pus 2 c# exception out

在设置 out 参数的值之前引发异常,然后尝试访问该参数时,C# 中定义的行为是什么?

public void DoSomething(int id, out control)
{
    try
    {
        int results = Call(Id);
        control = new CallControl(results);
    }
    catch(Exception e)
    {
      throw new Exception("Call failed", e);
    }
}

//somewhere else
DoSomething(out Control control)
{
    try
    {
       DoSomething(1, out control);
    }
    catch()
    {
    // handle exception
    }
}

// later
Control control;
DoSomething(out control)
control.Show();
Run Code Online (Sandbox Code Playgroud)

编译器通常会抱怨在设置 out 参数之前退出该方法。这似乎比它更聪明,无法保护我免受自己的伤害。

Jon*_*eet 5

在设置 out 参数的值之前引发异常,然后尝试访问该参数时,C# 中定义的行为是什么?

你不能这样做。该变量仍然不会被明确赋值,除非它在方法调用之前被明确赋值。

如果变量在方法调用之前被明确赋值,那么它仍然会被明确赋值 - 但除非方法在抛出异常之前赋值,否则变量的值将保持不变:

class Test
{
    static void JustThrow(out int x)
    {
        throw new Exception();
    }

    static void Main()
    {
        int y = 10;
        try
        {
            JustThrow(out y);
        }
        catch
        {
            // Ignore
        }
        Console.WriteLine(y); // Still prints 10
    }
}
Run Code Online (Sandbox Code Playgroud)