FXCop:“拥有一次性字段的类型应该是一次性的”

发布于 2024-07-22 16:39:49 字数 270 浏览 1 评论 0原文

我开始用 FXCop 来对付我的一些程序集,并注意到一些有趣的事情,我正在努力思考。

“声明一次性成员的类型 还应该实现 IDisposable。 如果 该类型不拥有任何非托管的 资源,不实施 终结器。”

包含一些控件,这些控件又继承自 System.Web.UI.WebControls.Button。这不是抱怨我继承的按钮,而是包装它们的类。

有什么影响或危险这里?

I started messing around with FXCop against some of my assemblies and noticed something interesting that I'm trying to wrap my head around.

"Types that declare disposable members
should also implement IDisposable. If
the type does not own any unmanaged
resources, do not implement a
finalizer on it."

I have my own class that contains some controls that in turn inherit from System.Web.UI.WebControls.Button. It's not complaining about my inherited buttons, but the class that wraps them is.

What's the impact or danger here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

呢古 2024-07-29 16:39:49

如果您的类包含 IDisposable 类型,但您的类不是 IDisposable,那么当不再需要您的类的实例时,您的类中的 IDisposable 类型可能不会按时释放/释放。
一旦不再需要 Dispoble 类型,就应立即将其丢弃,以便释放资源。 如果你不这样做,你将不得不等到 GC 启动,然后资源也会被释放。

If your class contains IDisposable types, but your class is not IDisposable, then it is possible that the IDisposable types within your class are not disposed / freed on time, when an instance of your class is no longer needed.
Dispoble types should be disposed as soon as you no longer need them, so that resources are freed. If you do not do that, you'll have to wait until the GC kicks in, then the resources will be freed as well.

只是我以为 2024-07-29 16:39:49

如您所知,当您使用完一次性对象后,您应该调用其 Dispose 方法。

当您从这些控件继承时,仍然可以调用 Dispose 方法。 但是如果您创建了一个包装器,那么包装器类的用户应该能够调用Dispose

public void Dispose() {
    button.Dispose();
    // any other thing that is disposable
}

As you know, when you finish using a disposable object, you should call its Dispose method.

When you inherit from these controls, it is still possible to call the Dispose method. But if you make a wrapper, then the user of your wrapper class should be able to call Dispose.

public void Dispose() {
    button.Dispose();
    // any other thing that is disposable
}
百思不得你姐 2024-07-29 16:39:49

包含按钮的类的性质是什么?

通常,我只期望作为复合控件的类具有其他控件作为成员。 这样的类通常直接或间接继承自 System.Web.UI.CompositeControl 或 System.Web.UI.WebControl,并且作为成员的控件应添加到 Controls 集合中。

这样做将确保它们得到正确处理,并且应该消除 FxCop 警告。

如果这没有帮助,请发布相关课程的更多详细信息。

What's the nature of the class that contains the buttons?

Normally I would only expect a class that's a composite control to have other controls as members. Such a class would normally inherit directly or indirectly from System.Web.UI.CompositeControl or System.Web.UI.WebControl, and the controls you have as members should be added to the Controls collection.

Doing so will ensure they are disposed properly and should get rid of the FxCop warning.

Post more details of the class in question if this doesn't help.

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