调试时强制 Dispose()
我知道这不是标准做法,但是执行以下操作是否有任何缺点或更好的替代方案?我只是想确保代码被正确使用,而 .NET 不会为您做任何事情来确保它。
public class MyClass : IDisposable
public void Dispose()
{
// Some managed shutdown logic...
GC.SuppressFinalize(this);
}
#if DEBUG
// Why is ConditionalAttribute not allowed if you can still achieve this with compiler directives?
// [Conditional("DEBUG")]
~SFtpClient()
{
Debug.Fail("This class is IDisposable and should be wrapped by using {}");
}
#endif
}
I know it isn't standard practice, but are there any downsides or better alternatives to doing the following? I just want to make sure the code is being used properly, and .NET doesn't do anything for you to ensure it.
public class MyClass : IDisposable
public void Dispose()
{
// Some managed shutdown logic...
GC.SuppressFinalize(this);
}
#if DEBUG
// Why is ConditionalAttribute not allowed if you can still achieve this with compiler directives?
// [Conditional("DEBUG")]
~SFtpClient()
{
Debug.Fail("This class is IDisposable and should be wrapped by using {}");
}
#endif
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 FxCop 并监视CA2000:在失去范围之前释放对象< /a>.
Use FxCop and watch for CA2000: Dispose objects before losing scope.
对我来说这看起来很好,因为该条件将防止在 RELEASE 版本中空 Finalizer 产生不必要的 Finalizing 成本。可能还想在 GC.SupressFinalize 周围添加 #if DEBUG。
[Conditional("DEBUG")] 告诉编译器不要调用该方法,但该方法仍然存在。无论如何,您无法编译调用 Finalize() 方法。 GC Finalizer 不检查该属性。
It looks good to me because that conditional will prevent the un-necessary Finalizing cost of an empty Finalizer in RELEASE builds. Might want to add the #if DEBUG around the GC.SupressFinalize, too.
The [Conditional("DEBUG")] tells the compiler not to call the method, but the method is still there. You can't compile a call the Finalize() method, anyway. The GC Finalizer doesn't check the attribute.