c# - 在 C# 中处理对象破坏的最佳方法是什么

标签 c# garbage-collection idisposable

我有一个类库项目,其中有一个在对象构造期间创建文件的类。对象完成后必须删除该文件。我已经实现了 IDisposable并在 Dispose() 中编写删除代码。问题是,我仍然看到该文件。我记得在某处读过 Dispose不保证会被调用。实现此目标的最佳方法是什么?

最佳答案

.NET 中的最佳实践是使用 using block 。我希望您不能保证如果有人编写了孤立代码,您的代码将始终被 GC;然而

Using Statement

Provides a convenient syntax that ensures the correct use of IDisposable objects.

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

using(YourDisposable iCanDispose = new YourDisposable())
{

  // work with iCanDispose
}

将确保在对象离开作用域后调用对象的 dispose 方法。

关于c# - 在 C# 中处理对象破坏的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849252/

相关文章:

c# - 内部范围内嵌套引用类型对象对垃圾回收没有影响 : True or False?

c# - 如果 using 语句抛出异常,我该如何处置 IDisposable 对象?

c# - 在自定义类中为 Entity Framework 实现IDisposable

c# - 运行单元测试时是否可以加载 launchSettings.json 文件中的配置文件?

c# - if 内的作用域变量

c# - MongoDB C# 驱动程序 - 将集合序列化为接口(interface)

c# - SOAP 使用不同的日期时间格式

java - HashMap 和垃圾回收 : do I need to call clear() before variable re-assignment?

java - 弱引用和强引用

c# - 如何更好地实现 .NET IDisposable 类?