因此,我正在为一个类的 MySQL 数据库制作一个客户端程序,并且我在表单类的顶部声明了一些变量,这些变量在表单的整个生命周期中都会使用和重用。每次使用变量时,我只是在做类似的事情:
variableName = new VariableClass();
然后使用它,主要用于 DataSets/Tables。我想知道的是我应该在再次调用 new 之前显式释放内存还是 C# 为我处理这个问题?
因此,我正在为一个类的 MySQL 数据库制作一个客户端程序,并且我在表单类的顶部声明了一些变量,这些变量在表单的整个生命周期中都会使用和重用。每次使用变量时,我只是在做类似的事情:
variableName = new VariableClass();
然后使用它,主要用于 DataSets/Tables。我想知道的是我应该在再次调用 new 之前显式释放内存还是 C# 为我处理这个问题?
无需在 C# 中显式释放 .Net 对象。它在 CLR 上运行,这是一个垃圾收集环境,因此将为您清理这些项目。
That being said ... it's unclear from your question if you are allocating these as fields or locals. If you are allocating them in fields and only using them in one function then you should move that declaration to a local. While the memory won't leak you will be holding onto the objects for significantly longer than is needed. This unnecessarily increases the memory footprint of your application.
It depends upon what the class of the variables does. If it uses resources that require disposal or if it uses unmanaged resources, you should implement IDisposable and ensure that they are disposed of correctly. If not, you can rely on the garbage collector to do its thing.