What should be passed as the objectName when throwing an ObjectDisposedException?

ⅰ亾dé卋堺 提交于 2019-12-18 13:51:36

问题


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?


回答1:


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.




回答2:


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);
}



回答3:


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).



来源:https://stackoverflow.com/questions/1964496/what-should-be-passed-as-the-objectname-when-throwing-an-objectdisposedexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!