c# - 在没有设置参数的情况下抛出异常时的行为是什么?

标签 c# exception 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();

编译器通常会在设置 out 参数之前提示退出方法。这似乎使它无法保护我免受自己的伤害。

最佳答案

What is the defined behaviour in C# for when an exception is thrown before setting the value of an out parameter, and you then try to access the parameter?

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

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

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

关于c# - 在没有设置参数的情况下抛出异常时的行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21825556/

相关文章:

c# - 使用 C# 和 .NET 进行审计

java - C# 中的 readInt16() 与 java 中的 readShort()

php - 如何禁用 PHP 在异常堆栈跟踪中切断部分长参数?

html - 移除可点击 HTML 元素上的框架

c# - 在 C# 中什么都不做关键字?

c# - MSTest 显示复合 bool 表达式的部分代码覆盖率

android - SharedPreferences getLong() -> java.lang.String 无法转换为 java.lang.Long。怎么修?

java - 无法复制 : "Comparison method violates its general contract!"

c# - 带有 out 参数的最小起订量回调

audio - 捕获音频以用于网页