试图了解“使用”的语句更好 [英] Trying to understand the 'using' statement better

查看:135
本文介绍了试图了解“使用”的语句更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过一对夫妇约using语句,试图了解何时应该使用它的文章。它听起来像大多数人估计它应该被用来尽可能多的,因为它保证了处置闲置对象

I have read a couple of articles about the using statement to try and understand when it should be used. It sound like most people reckon it should be used as much as possible as it guarantees disposal of unused objects.

问题是,所有的例子总是显示是这样的:

Problem is that all the examples always show something like this:

using (SqlCommand scmFetch = new SqlCommand())
{
    // code
}

这是有道理的,但它是这么小的一段代码。我应该在数据库上执行查询时,怎么办?什么是所有的步骤?它会是这个样子:

That makes sense, but it's such a small piece of code. What should I do when executing a query on a database? What are all the steps? Will it look something like this:

string sQuery = @"
    SELECT [ID], [Description]
    FROM [Zones]
    ORDER BY [Description] ";

DataTable dtZones = new DataTable("Zones");

using (SqlConnection scnFetchZones = new SqlConnection())
{
    scnFetchZones.ConnectionString = __sConnectionString;
    scnFetchZones.Open();

    using (SqlCommand scmdFetchZones = new SqlCommand())
    {
        scmdFetchZones.Connection = scnFetchZones;
        scmdFetchZones.CommandText = sQuery;

        using (SqlDataAdapter sdaFetch = new SqlDataAdapter())
        {
            sdaFetch.SelectCommand = scmdFetchZones;
            sdaFetch.Fill(dtZones);
        }
    }

    if (scnFetchZones.State == ConnectionState.Open)
        scnFetchZones.Close();
}



我想知道的是:

•什么情况下可以有4个,5个,10嵌套using语句,以确保所有的物品设置?

•在什么时候我做错了什么,我应该考虑修改?

•如果修订的由于太多的嵌套使用语句所需,我有哪些选择?


你可能最终得到一个强大的等级,但你的代码应该是相当有效的,对不对?或者你只能说,例如,的SqlDataAdapter 对象using语句,它会以某种方式确保所有其他对象得到处置呢?

What I want to know is:
• Is it okay to have 4, 5, 10 nested using statements to ensure all objects are disposed?
• At what point am I doing something wrong and should I consider revision?
• If revision is required due to too many nested using statements, what are my options?

You might end up with a formidable hierarchy, but your code should be quite efficient, right? Or should you only put, for instance, the SqlDataAdapter object in a using statement and it will somehow ensure that all the other objects get disposed as well?

感谢名单

推荐答案

这是最有效的办法有很多using语句嵌套的:

It is perfectly valid to have many nested using statements:

using(A a = new A())
using(B b = new B())
{
   a.SomeMethod(b);
}

这篇关于试图了解“使用”的语句更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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