Trying to understand the 'using' statement better

后端 未结 8 1240
小鲜肉
小鲜肉 2021-01-18 17:26

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 possib

相关标签:
8条回答
  • 2021-01-18 17:35

    IMHO, what you need to ask yourself is: What are the alternatives? Try/finally blocks? Are they more readable? More maintainable? In almost all cases, the answer is going to be "no".

    So use using. It's the closest thing C# has to C++'s RAII pattern and it's all good :-)

    0 讨论(0)
  • 2021-01-18 17:38

    There's no limit on the depth, so that's not a concern. You should verify that the object of the using implements IDisposable. And an object being disposed doesn't dispose of all objects connected to it, just those it creates.

    So, at what point are you doing wrong: there's no limit, but generally its fairly shallow, you create the object, do a task, then the object is disposed. If you're doing it very deeply, I'd look at the design. I think you'd be hard pressed to do it more than few layers deep.

    As for your options for a redesign, that really depends upon what you are doing, but you might use the same object for multiple tasks. Most likely you will end up breaking the task down into a function (passing in any surrounding objects that are needed).

    0 讨论(0)
  • 2021-01-18 17:40

    Personally, I have used at least 3 layers (Connection, Command, Other) a number of times and I see absolutely no problem with it, but as you have already hinted at, eventually there will be a problem a readability. As with other nested constructs, you may need to balance efficiency with maintainability. That is, you don't need to necessarily sacrifice efficiency, but there is often 'more than one way to skin a cat'.

    That said, you would be hard-pushed to generate 10 nested layers!

    0 讨论(0)
  • 2021-01-18 17:52

    It is perfectly valid to have many nested using statements:

    using(A a = new A())
    using(B b = new B())
    {
       a.SomeMethod(b);
    }
    
    0 讨论(0)
  • 2021-01-18 17:58

    • Is it okay to have 4, 5, 10 nested using statements to ensure all objects are disposed?

    Reply: You can not limit of using nested "using blocks ".

    • At what point am I doing something wrong and should I consider revision?

    Reply: If you have many nested "using blocks". Please try as below.

            using (var con = new SqlConnection(connStr))
            using (var cmd = new SqlCommand(queryStry))
            using (var rs = cmd.ExecuteReader())
            {
                while (rs.Read())
                {
                    //Code.
                }
            }
    
    0 讨论(0)
  • 2021-01-18 17:59

    You would never be wrong if you use using for every IDisposable that you use. There is no limit of how many nested using blocks you use.

    0 讨论(0)
提交回复
热议问题