正确实现一次性模式 - 自动实现的属性
实现 Dispose 方法的规则之一是:
当资源已释放时,从此类型的实例方法(
Dispose
除外)抛出ObjectDisposeException
。此规则不适用于Dispose
方法,因为它应该可以多次调用而不会引发异常。
请参阅:http://msdn.microsoft.com/en-us/library/ b1yfkh5e.aspx
这是否意味着如果我想正确实现属性,我就不能使用自动实现的属性?我是否需要像这样实现它的属性?
private bool _property;
public bool Property
{
get
{
if(disposed) throw new ObjectDisposedException("MyClass");
return _property;
}
set
{
if(disposed) throw new ObjectDisposedException("MyClass");
_property=value;
}
}
One of the rules for implementing the Dispose
method says:
Throw an
ObjectDisposedException
from instance methods on this type (other thanDispose
) when resources are already disposed. This rule does not apply to theDispose
method because it should be callable multiple times without throwing an exception.
See: http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx
Does this mean that if I want to implement properties correctly, I cannot use auto-implemented properties? Do I need properties that implement it like this one?
private bool _property;
public bool Property
{
get
{
if(disposed) throw new ObjectDisposedException("MyClass");
return _property;
}
set
{
if(disposed) throw new ObjectDisposedException("MyClass");
_property=value;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,属性应该像字段一样(很少或没有计算,如果其他状态没有更改,则在多次调用中返回相同的值),因此它们不需要完整的处置检查,但您应该对定义的公共方法进行检查班级。
Generally, properties should act like fields (little or no computation, return the same value over multiple calls if no other state has changed), so they don't need the full dispose check, but you should put checks on defined public methods in your class.
这取决于。调用已处置的对象是一个边缘条件,因此您通常不希望在常规使用期间通过添加所有这些测试来牺牲对象的效率。
正确的阅读规则的方法是:
ObjectDisposeException如果类的 Dispose 方法将某个字段设置为 null,您应该从使用该字段的方法/属性中抛出
ObjectDisposeException
,而不是因NullReferenceException
失败。It depends. Calling a disposed object is an edge condition so you usually won't want to sacrifice your object's efficiency during regular use by adding all those tests.
The correct way to read the rule is:
E.g. If the Dispose method of your class sets some field to null you should throw an
ObjectDisposedException
from methods/properties using that field instead of failing with aNullReferenceException
.