真正发生在try {返回X; }终于{X = NULL; } 声明? [英] What really happens in a try { return x; } finally { x = null; } statement?

查看:135
本文介绍了真正发生在try {返回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; }

我的意思是,在最后子句真正执行的 的的返回语句之后?如何线程安全的是这样的code?你能想到的任何额外的两轮牛车,可以做WRT这个尝试,终于破解?

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 {返回X; }终于{X = NULL; } 声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆