【发布时间】:2020-04-29 12:20:15
【问题描述】:
我正在关注一个帖子示例,其中我有一个像 MyService 这样的服务并被包装在 using 关键字 like 中
(using MyService = new MyService())
{
}
编译后,编译器抱怨服务需要实现 IDisposable 所以我添加了
public class MyService : IDisposable
{
void IDisposable.Dispose()
{
}
}
编译器没有抱怨,“使用”实现似乎正在工作,但我被告知这是错误的实现。我从这里的一篇文章中得到了 IDisposable.Dispose() 。现在大多数帖子都有添加公共无效处置(处置)的实现。
我正在寻找一种更简单的 Dispose 方法,而不是一些服务中的多种方法。 有没有更简单的方法?
谢谢
【问题讨论】:
-
After building, the compiler complained about the service needing to implement IDisposable so I added,如果您不需要实现IDisposable,那么不要将您的服务实例化包装在using语句中。using块的唯一 目的是语法糖,以确保最后调用Dispose()(即使抛出异常)。 -
Visual Studio 2019 很乐意为您自动实现它,如果您只需打开代码提示(Ctrl+.,或单击灯泡,当插入符号位于
Dispose()方法的行上时) . -
“但有人告诉我这是错误的实现” - 问他们为什么。我没有看到implicit interface implementation 有问题,也没有看到其他代码来判断。
-
@Sinatr OP 正在使用显式接口实现。虽然
using子句无关紧要,但在对象本身上使用Dispose会更方便。并且,当使用这个short form of the Dispose pattern 时,该类应该被标记为sealed,它不是。