3

出于实用性考虑,这两个课程都是一次性的。

我了解 using 块的作用。但我不确定它可以或需要使用的所有方式。

例如,这是正确的吗?

using (MyClass myClass = new MyClass(params))
{
     myClass.name = "Steve";

     SecondClass myClassSecond = new SecondClass(params);
     myClassSecond.name = "George";
     myClassSecond.msg = "Hello Man in the Yellow Hat";
}

上面的两个类都被处理了吗?

或者我是否需要在 using 语句中?

using (MyClass myClass = new MyClass(params))
{
     myClass.name = "Steve";

     using (SecondClass myClassSecond = new SecondClass(params))
     {
          myClassSecond.name = "George";
          myClassSecond.msg = "Hello Man in the Yellow Hat";
     }
}

以上是正确的,还是有更好的方法来使用多个 using 语句?

4

9 回答 9

3

Your second example is proper assuming SecondClass is indeed dispoable. If it is the first example is not correct as mySecondClass will not be disposed of. If a block of code controls the lifetime of a disposable instance it should always dispose of it.

FYI I prefer this style for disposing multiple objects in the same block as I find it more readable.

using (MyClass myClass = new MyClass(params))
using (SecondClass myClassSecond = new SecondClass(params))     
{
     myClassSecond.name = "George";
     myClassSecond.msg = "Hello Man in the Yellow Hat";     
}

Both usings share the same scope and Dispose in reverse order of declaration.

于 2013-06-12T15:14:14.790 回答
3

Using blocks are handy when you are working with anything that implements IDisposable interface. MSDN:

[using Statement] Defines a scope, outside of which an object or objects will be disposed.

So, these is effectively an equivalent of

IDisposable resource = new Whatever();
try {
    // whatever
}
finally {
    resource.Dispose();
}

The primary advantages of using are: it automatically disposes the object upon leaving the using block, so (1) you won't forget to do it and (2) it does the cleanup in case of exception.

Short rules:

  • Anytime you open a file/database connection or create an instance of class that needs any kind of cleanup - do it in using block.
  • If the lifetime of the object should extend the method scope - wrap it in a class, implement IDisposable in that class, instantiate a resource in constructor, cleanup in Dispose.
于 2013-06-12T15:14:47.083 回答
3
  • The using statement allows the programmer to specify when objects that use resources should release them.
  • The object provided to the using statement must implement the IDisposable interface.
  • This interface provides the Dispose method, which should release the object's resources.

Here is the sample showing use of using statement:

using System;
//Object of this class will be given to using hence IDisposable
class C : IDisposable        
{
    public void UseLimitedResource()
    {
        Console.WriteLine("Using limited resource...");
    }

    //Dispose() Method
    void IDisposable.Dispose()
    {
        Console.WriteLine("Disposing limited resource.");
    }
}

class Program
{
    static void Main()
    {
        using (C c = new C())  //Object of Class defined above
        {
            c.UseLimitedResource();
            //Object automatically disposed before closing.
        }                            
        Console.WriteLine("Now outside using statement.");
        Console.ReadLine();
    }
}

A using statement can be exited either when:

  • the end of the using statement is reached or
  • if an exception is thrown and control leaves the statement block before the end of the statement.

Which is proper method?

As you are saying that

Both classes for practicality sake are disposable

., then your second approach is the appropriate one. that is:

using (MyClass myClass = new MyClass(params))
{
     myClass.name = "Steve";

     using (SecondClass myClassSecond = new SecondClass(params))
     {
          myClassSecond.name = "George";
          myClassSecond.msg = "Hello Man in the Yellow Hat";
     }
}
于 2013-06-12T15:15:13.320 回答
2

A using block does not automatically dispose any child objects that implement IDisposable. You have to wrap inner disposables in using blocks if you want them disposed. You do, however, have a few different options for this.

You could nest multiple using blocks and they are evaluated inner-most to outer-most. There is a better way to do this, but the following example works:

using (MyClass myClass = new MyClass(parameters))
{
     using (SecondClass myClassSecond = new SecondClass(parameters))
     {
          myClassSecond.name = "George";
          myClassSecond.msg = "Hello Man in the Yellow Hat";
     }
}

If the declarations are consecutive and you don't need to do anything in between, the following syntax is more succinct:

using (MyClass myClass = new MyClass(parameters))
using (SecondClass myClassSecond = new SecondClass(parameters))
{
    myClassSecond.name = "George";
    myClassSecond.msg = "Hello Man in the Yellow Hat";
}

If you need to do something in between the declarations, then your latter example is correct:

using (MyClass myClass = new MyClass(parameters))
{
     myClass.name = "Steve";

     using (SecondClass myClassSecond = new SecondClass(parameters))
     {
          myClassSecond.name = "George";
          myClassSecond.msg = "Hello Man in the Yellow Hat";
     }
}
于 2013-06-12T15:18:01.860 回答
0

The simple answer is if the class has a dispose method, use using.

http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx

If it does not, no need.

http://msdn.microsoft.com/en-us/library/system.random.aspx

I've always wished this was more in your face in the MSDN documentation. At the end of the day, it's the classes that implement IDisposable, but really what I want is some sort of giant icon on the page that in some way says. 'Pay attention dummy! You must manage this yourself!'

于 2013-06-12T15:13:54.190 回答
0

IDisposable如果我创建的类使用大量资源,或者我创建它作为文件处理或网络资源的包装器,我喜欢在我创建的类中实现。

using在我使用的类对象中,如果有问题的对象打开文件、创建网络连接等,我认为用块调用很重要。

一些开发人员会编写一个实现的类,IDisposable这样他们就可以将他们的代码放在看起来更干净的using块中,但我认为这滥用了创建 Disposable 的东西的原因。

于 2013-06-12T15:20:59.067 回答
0

我的经验法则是……如果它实现了一次性,我使用 using 块。

总是比抱歉更安全。

为了回答你的问题,我会选择第二个选项。

于 2013-06-12T15:13:16.137 回答
0

using块纯粹是一种处理 IDisposable 对象的语法简单方法。如果您了解做什么using,那么您应该了解它可以并且应该如何使用。

using请参阅此问题以了解该块被翻译成 的确切内容: Uses of "using" in C#

于 2013-06-12T15:15:58.050 回答
0

这取决于这些类是什么以及它们如何处理所使用的任何资源。该using语句本质上与块 (no ) 相同,try/finally块 (no catch) 在块中处理其资源finally(通过调用.Dispose()相关对象)。

所以,首先,如果有问题的类没有实现IDisposable,那么这是一个有争议的问题,在这种情况下你不能在一个using块中使用它。如果它确实实现IDisposable了,那么它可能是有原因.Dispose()的,当你完成它时应该在该对象上调用它。在这些情况下,谨慎的做法是将其包装在一个using块中以保证处置。(好吧,“保证”只要finally块将被执行。通常情况就是这样,除非发生了更糟糕的事情。)

于 2013-06-12T15:16:01.287 回答