在 try { return x; 中真正发生了什么?} 最后 { x = n

What really happens in a try { return x; } finally { x = null; } statement?(在 try { return x; 中真正发生了什么?} 最后 { x = null;} 陈述?)
本文介绍了在 try { return x; 中真正发生了什么?} 最后 { x = null;} 陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个问题中看到了这个提示,想知道是否有人可以向我解释这到底是如何工作的?

I saw this tip in another question and was wondering if someone could explain to me how on earth this works?

try { return x; } finally { x = null; }

我的意思是,finally 子句真的执行 after return 语句吗?这段代码有多线程不安全?你能想到任何可以做的额外黑客行为吗?这个 try-finally 破解?

I mean, does the finally clause really execute after the return statement? How thread-unsafe is this code? Can you think of any additional hackery that can be done w.r.t. this try-finally hack?

推荐答案

不 - 在 IL 级别,您不能从异常处理块内部返回.它本质上将它存储在一个变量中,然后返回

No - at the IL level you can't return from inside an exception-handled block. It essentially stores it in a variable and returns afterwards

即类似于:

int tmp;
try {
  tmp = ...
} finally {
  ...
}
return tmp;

例如(使用反射器):

static int Test() {
    try {
        return SomeNumber();
    } finally {
        Foo();
    }
}

编译为:

.method private hidebysig static int32 Test() cil managed
{
    .maxstack 1
    .locals init (
        [0] int32 CS$1$0000)
    L_0000: call int32 Program::SomeNumber()
    L_0005: stloc.0 
    L_0006: leave.s L_000e
    L_0008: call void Program::Foo()
    L_000d: endfinally 
    L_000e: ldloc.0 
    L_000f: ret 
    .try L_0000 to L_0008 finally handler L_0008 to L_000e
}

这基本上声明了一个局部变量(CS$1$0000),将值放入变量中(在处理的块内),然后在退出块后加载变量,然后返回它.反射器将其呈现为:

This basically declares a local variable (CS$1$0000), places the value into the variable (inside the handled block), then after exiting the block loads the variable, then returns it. Reflector renders this as:

private static int Test()
{
    int CS$1$0000;
    try
    {
        CS$1$0000 = SomeNumber();
    }
    finally
    {
        Foo();
    }
    return CS$1$0000;
}

这篇关于在 try { return x; 中真正发生了什么?} 最后 { x = null;} 陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)