抛出 ObjectDisposeException 时应该传递什么作为 objectName?

发布于 2024-08-16 06:51:49 字数 113 浏览 3 评论 0原文

在实现 IDisposable 时,我知道在对象被释放后不应调用的每个方法都应抛出 ObjectDispositedException。但是应该传递给异常构造函数的名称对象的标准是什么?

When implementing IDisposable, I undertand that every method that shouldn't be called after the object's been disposed should throw the ObjectDisposedException. But what is the standard for the name object that should be passed to the exception's constructor?

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

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

发布评论

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

评论(3

萌无敌 2024-08-23 06:51:49

我相信推荐的做法是抛出以下内容:

throw new ObjectDisposedException(GetType().FullName);

或者包括检查,这两行代码位于需要它的每个方法的顶部(显然不是 Dispose 方法本身):

if (this.disposed)
    throw new ObjectDisposedException(GetType().FullName);

甚至可能会有所帮助将其重构为一个小方法以提高可用性。

I believe the recommended practice is to throw the following:

throw new ObjectDisposedException(GetType().FullName);

Or including the check, these two lines of code at the top of each method that needs it (obviously not the Dispose method itself):

if (this.disposed)
    throw new ObjectDisposedException(GetType().FullName);

Might even be helpful to refactor this into a tiny method for usability.

差↓一点笑了 2024-08-23 06:51:49

甚至 .NET Framework 本身在这里也不是很一致。

David M. Kean(Microsoft FxCop 团队的前开发人员)向 ObjectDisposeException 的 MSDN 文档

这种类型的典型用法如下:

<前><代码>[C#]
私人无效检查处置()
{
抛出新的 ObjectDisposeException(GetType().FullName);
}

Even the .NET Framework itself isn't very consistent here.

David M. Kean (former developer on the FxCop team at Microsoft) added a comment to the MSDN documentation for the ObjectDisposedException:

The typical usage of this type is something like the following:

[C#]
private void CheckDisposed()
{
    throw new ObjectDisposedException(GetType().FullName);
}
镜花水月 2024-08-23 06:51:49

我不相信有一个标准,我会返回对象的类型以及唯一标识字段(某种“主键”)的字符串内容。

I don't believe there's a standard for that, I would return the type of the object along with the string content of a unique identifying field (a 'Primary Key' of sorts).

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