处置存储在一个公共静态字段中的IDisposable对象 [英] Disposing an IDisposable object stored in a public static field

查看:139
本文介绍了处置存储在一个公共静态字段中的IDisposable对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个类实现了IDisposable则包含类实现IDisposable和类的字段Dispose方法从它的Dispose方法中。一个实例字段

If a class has an instance field that implements IDisposable then the containing class implements IDisposable and class that fields Dispose method from within its Dispose method.

public class A : IDisposable 
{
    public System.Drawing.Font font = new Font("Arial", 10.0f);

    public void Dispose()
    {
        font.Dispose()
    }
}

(我知道我没有做正确的处置方式,但对于样品code应该是足够了)

(I know I didn't do the dispose pattern correctly, but for sample code should be good enough)

如果该字段是一个静态字段,虽然应该在哪里调用到现场的处置是什么?

If the field is a static field though where should the call to the field's Dispose be?

public class B
{
    public static System.Drawing.Font font = new Font("Arial", 10.0f);
}

我可以做B类实现IDisposable,并有电话 font.Dispose ,但如果B.font再次使用以后会导致问题。除了你必须记住,dispise访问你只是需要创建一个实例调用Dispose一个静态方法。

I could make class B implement IDisposable and have that call font.Dispose but if B.font is used again later on that would cause problems. As well as you'd have to remember that dispise accessing a static method you need to create an instance just to call Dispose.

我也可以做一个静态的Dispose方法但用户必须记住调用Dispose,并必须确保他们的它在节目的最后一个用户。

I could also make a static Dispose method but then users have to remember to call Dispose and have to make sure they're the last user of it in the program.

推荐答案

静态字段当类型加载初始化。

Static fields are initialised when the type is loaded.

因此​​,它在逻辑上是有意义的处置分配时,包含类型被卸载的静态字段的对象。

Therefore it logically it makes sense to dispose the object assigned to the static field when the containing type is unloaded.

不过,类型不卸载。可能有一些异国情调的并发症这里周围的AppDomain,但我怀疑,这并不在你的情况适用。

However, types are not unloaded. There may be some exotic complication here around AppDomains, but I suspect that doesn't apply in your case.

因此​​,我不会处理的情况下,否则你将有一个对象的一个​​公开的实例,它是不宜使用。

Therefore I wouldn't dispose the instance, otherwise you will have a publicly available instance of an object that is unfit for use.

这篇关于处置存储在一个公共静态字段中的IDisposable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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