请问C#编译器会自动处理IDisposable的对象? [英] Does the C# compiler automatically dispose of IDisposable objects?

查看:88
本文介绍了请问C#编译器会自动处理IDisposable的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个方法公共静态矩形的DrawRectangle(矢量产地,矢量大小)返回类型的对象矩形:IDisposable的

Assuming I have a method public static Rectangle DrawRectangle(Vector origin, Vector size) which returns an object of type Rectangle : IDisposable

如果我只调用方法的DrawRectangle(产地,规格),但不分配返回值给一个变量 myRectangle =的DrawRectangle(出身,尺寸),将编译器会自动检测到,并调用的DrawRectangle(产地,规格).Dispose(),还是我必须这样做我自己?

If I call only the method DrawRectangle(origin, size), but do not assign the return value to a variable myRectangle = DrawRectangle(origin, size), will the compiler automatically detect this and call DrawRectangle(origin, size).Dispose(), or do I have to do it myself?

推荐答案

有只有两种情况下我能想到的在这里编译器会自动调用Dispose;最明显的是:

There are only two scenarios I can think of where the compiler automatically calls dispose; the most obvious would be:

using(var obj = ... )
{
  // some code
}

这是一个明确的指示说末,无论是成功还是失败,如果 OBJ 非空,调用 obj.Dispose ()。基本上,它扩展为:

which is an explicit instruction to say "at the end, whether success or failure, if obj is non-null, call obj.Dispose()". Basically it expands to:

{
   var obj = ...
   try {
       // some code
   } finally {
       if(obj != null) obj.Dispose();   
   }
}

另外就是的foreach ,其中,由迭代器设置 - 虽然它变得有点复杂,因为的IEnumerator 未指定的IDisposable 是必需的(相比之下,的IEnumerator< T> 确实指定),并在技术上的IEnumerable 甚至不要求的foreach ,但基本上是:

The other is foreach, where-by the iterator is disposed - although it gets a bit complicated, because IEnumerator doesn't specify that IDisposable is required (by contrast, IEnumerator<T> does specify that), and technically IEnumerable is not even required for foreach, but basically:

foreach(var item in sequence) {
   // some code
}

可能是pssed作为前$ P $(尽管该规范可以说是略有不同):

could be expressed as (although the spec may say it slightly differently):

{
    var iter = sequence.GetEnumerator();
    using(iter as IDisposable)
    {
        while(iter.MoveNext())
        {   // note that before C# 5, "item" is declared *outside* the while
            var item = iter.Current;
            // some code
        }
    }
}

在所有其他情况下,配置资源的的责任。

In all other cases, disposing resources is your responsibility.

如果您不能确保的Dispose()被调用,那么什么都不会发生,直到GC最终收集的对象; 如果有一个终结器(有没有要,而且通常不是),终结器将被调用 - 但是,这是不同的的Dispose()。它的可以(根据每个类型的实现),最终会做同样的事情,的Dispose():但也可能不是。

If you don't ensure that Dispose() is called, then nothing will happen until GC eventually collects the object; if there is a finalizer (there doesn't have to be, and usually isn't), the finalizer will be invoked - but that is different to Dispose(). It may (depending on the per-type implementation) end up doing the same thing as Dispose(): but it may not.

这篇关于请问C#编译器会自动处理IDisposable的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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