开发者

Using "using" statement to dispose

Does this make sense ?

Having a simple class

   class Test
   {
     public Test()
     {
        // Do whatev开发者_如何学运维er
     }
   }

and then instantiating it

using(new Test())
{
  // Nothing in here
}

The using statement is there just to make sure Test is disposed. When will it be disposed if I just call

new Test()


Test isn't IDisposable, so that won't even compile. But if it was disposable, yes using will do it, and new by itself won't. It is an unusual usage, but I've seen similar. Rarely.

Based on your comment (main question), I suspect that you are confusing garbage collection and disposal. There is no way to forcibly make something get collected, short of GC (which you should not do). Unless you have a really good reason to want it collected, just let it be - chances are it is "generation 0" and will be collected cheaply anyway.

Also, the "do whatever" suggests doing something in a constructor but not caring about the created object; a static method would be preferable:

public class Test { /* could be static */
     public static void DoSomething() { ... }
}
...
Test.DoSomething();


By not assigning the instance to a variable, it will be eligible for GC as soon as it goes out of scope.

Or, is there something else you are trying to accomplish with this?


Recommended reading:

http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜