简体   繁体   English

C#:将子级设置为null时父母处置?

[英]C#: Setting child class to null on parents dispose?

Is my implementation of dispose correct? 我的处置方法正确吗? In this question I'm sort of asking 1 question but about 1 topic to understand it better. 在这个问题中,我想问一个问题,但要问一个话题才能更好地理解它。

  • Do I need to set lists, dictionarys and any type of collection to null on dispose? 是否需要在处理时将列表,字典和任何类型的集合设置为null?
  • Do I need to clear collections on dispose? 我是否需要清除收集中的垃圾?
  • Do I need to set child class to null on dispose? 处理时是否需要将子类设置为null?

Take this code for example.. 以下面的代码为例。

public class ParentClass : IDisposable
{
    private readonly ChildClass;

    public ParentClass()
    {
        ChildClass = new ParentClass();
    }

    public void Dispose()
    {
        ChildClass.Dispose();
        ChildClass = null;
    }
}

public class ChildClass : IDisposable
{
    private Dictionary<int> myIds;

    public ChildClass()
    {
        myIds = new Dictionary<int>();
    }

    public void Dispose()
    {
        myIds.Clear();
        myIds = null;
    }
}

The answer to all your questions is no . 您所有问题的答案是否定的 .NET programs use managed code, which means the platform will clean up all these objects for you. .NET程序使用托管代码,这意味着平台将为您清理所有这些对象。

Now, if you access an unmanaged resource such as a file, database, etc. That's when you need to use IDisposable to ensure that any unmanaged resources get cleaned up in a timely manner. 现在,如果您访问文件,数据库等非托管资源,则需要使用IDisposable来确保及时清理所有非托管资源。

But things like Dictionary<> will clean up themselves. 但是像Dictionary<>这样的东西会自行清理。

Whether members should be set to null in Dispose() can be answered in different ways. 可以用不同的方式回答是否在Dispose()中将成员设置为null。 It's (as said in many other answers - see "Related" on the right) only necessary for members that are on itself disposable. (如许多其他答案所述-参见右侧的“相关”)仅对于本身是一次性的成员是必需的。

First, it's obviously only possible to set a member to null in Dispose() if it is not declared as readonly. 首先,如果未将成员声明为只读,则很可能仅在Dispose()中将成员设置为null。 Making them not readonly just because of this is probably not a good design pattern. 因此,仅将它们设置为非只读可能不是一个好的设计模式。 If you do set it to null after dispose, you also have to check for null before doing so, because you must always be able to call Dispose() multiple times without side effects or exceptions. 如果确实在处理之后将其设置为null,则还必须在执行此操作之前检查是否为null,因为您必须始终能够多次调用Dispose()且没有副作用或异常。 Setting a member to null also helps in preventing that you accidentally use the object again after dispose (because accessing the member will cause an exception). 将成员设置为null还有助于防止在处置后再次意外使用该对象(因为访问该成员将导致异常)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM