调试时强制 Dispose()

发布于 2024-11-14 15:45:36 字数 563 浏览 4 评论 0原文

我知道这不是标准做法,但是执行以下操作是否有任何缺点或更好的替代方案?我只是想确保代码被正确使用,而 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝海似她心 2024-11-21 15:45:36

对我来说这看起来很好,因为该条件将防止在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文