从 using() 语句内部返回有任何副作用吗?

发布于 2024-08-24 00:38:46 字数 742 浏览 2 评论 0原文

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

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

但我总觉得我应该关闭某些内容< /strong> 在我打破 using 括号之前,例如通过在 using 语句之前定义事务,在括号内部获取它的值,然后返回之后< /strong> 括号。

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

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

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.

Would defining and returning the variable outside the using brackets be better practice or conserve resources in any way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

┊风居住的梦幻卍 2024-08-31 00:38:46

不,我认为这样更清楚。不用担心,Dispose 仍会在“退出时”被调用 - 并且仅在返回值完全计算之后。如果在任何时候抛出异常(包括评估返回值),Dispose 仍然会被调用。

虽然您当然可以采取更长的路线,但这是两条额外的线,只是增加了多余的内容和额外的上下文来跟踪(精神上)。事实上,您并不真正需要额外的局部变量 - 尽管它在调试方面很方便。您可以:

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 中:

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

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();
    }
}

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);
    }
}
滥情哥ㄟ 2024-08-31 00:38:46

看一下

了解 C# 中的“using”语句

CLR 将您的代码转换为 MSIL。
using 语句得到
翻译成尝试和最后
堵塞。这就是 using 语句的方式
以 IL 表示。一个使用
声明被翻译成三个
部分:获取、使用和
处理。资源是第一位的
获取,然后附上用法
在带有finally的try语句中
条款。然后该对象被处置
在finally子句中。

Have a look at this

Understanding the 'using' statement in C#

The CLR converts your code into MSIL.
And the using statement gets
translated into a try and finally
block. This is how the using statement
is represented in IL. A using
statement is translated into three
parts: acquisition, usage, and
disposal. The resource is first
acquired, then the usage is enclosed
in a try statement with a finally
clause. The object then gets disposed
in the finally clause.

最终幸福 2024-08-31 00:38:46

using() 语句内部返回没有副作用。

是否能生成最具可读性的代码是另一个讨论。

There are no side effects of returning from inside a using() statement.

Whether it makes the most readable code is another discussion.

香草可樂 2024-08-31 00:38:46

我想,都是一样的。代码中没有什么不好的地方。 .NET 框架不关心对象是在哪里创建的。重要的是它是否被引用。

I think, it's all the same. There's nothing bad in the code. The .NET framework wouldn't care where the object is created. The thing that matters is whether it is referenced or not.

狼亦尘 2024-08-31 00:38:46

是的,可能会有副作用。例如,如果您在 ASP.NET MVC Action 方法中使用相同的技术,您将收到以下错误:“ObjectContext 实例已被释放,无法再用于需要连接的操作”

public ActionResult 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 PartialView("_transactionPartial", transaction);
    }
}

Yes, there can be a side effect. For example, if you use the same technique in ASP.NET MVC Action method, you will get the following error: "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"

public ActionResult 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 PartialView("_transactionPartial", transaction);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文