从 using() 语句内部返回是否有任何副作用? [英] Are there any side effects of returning from inside a using() statement?

查看:28
本文介绍了从 using() 语句内部返回是否有任何副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从获取 DataContext 的 using 语句内部返回方法值似乎总是正常,如下所示:

Returning a method value from inside a using statement that gets a DataContext seems to always work fine, like this:

public static Transaction GetMostRecentTransaction(int singleId)
{
    using (var db = new DataClasses1DataContext())
    {
        var transaction = (from t in db.Transactions
                              orderby t.WhenCreated descending
                              where t.Id == singleId
                              select t).SingleOrDefault();
        return transaction;
    }
}

但我总是觉得我应该在退出 using 括号之前关闭某些东西,例如通过在 using 语句之前定义事务,获取它的值括号内,然后在括号之后返回.

But I always feel like I should be closing something before I break out of the using brackets, e.g. by defining transaction before the using statement, get it's value inside the brackets, and then returning after the brackets.

在使用方括号之外定义和返回变量是否是更好的做法或以任何方式节省资源?

推荐答案

不,我认为这样更清楚.不用担心,Dispose 仍然会在出路时"被调用——并且只有在之后 返回值被完全评估.如果在任何时候抛出异常(包括评估返回值)Dispose 仍将被调用.

No, I think it's clearer this way. Don't worry, Dispose will still be called "on the way out" - and only after the return value is fully evaluated. If an exception is thrown at any point (including evaluating the return value) Dispose will still be called too.

虽然你当然可以走更长的路线,但这是两条额外的线路,只是添加了粗俗和额外的上下文来跟踪(精神上).事实上,您并不真正需要额外的局部变量——尽管它在调试方面很方便.你可以:

While you certainly could take the longer route, it's two extra lines that just add cruft and extra context to keep track of (mentally). In fact, you don't really need the extra local variable - although it can be handy in terms of debugging. You could just have:

public static Transaction GetMostRecentTransaction(int singleId)
{
    using (var db = new DataClasses1DataContext())
    {
        return (from t in db.Transactions
                orderby t.WhenCreated descending
                where t.Id == singleId
                select t).SingleOrDefault();
    }
}

事实上,我什至可能想使用点表示法,并将 Where 条件放在 SingleOrDefault 中:

Indeed, I might even be tempted to use dot notation, and put the Where condition within the SingleOrDefault:

public static Transaction GetMostRecentTransaction(int singleId)
{
    using (var db = new DataClasses1DataContext())
    {
        return db.Transactions.OrderByDescending(t => t.WhenCreated)
                              .SingleOrDefault(t => t.Id == singleId);
    }
}

这篇关于从 using() 语句内部返回是否有任何副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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