如何重写 Dispose 方法并将 dippedValue 设为 Private?
我必须将一些 Dispose 代码添加到继承自已实现 IDisposable 的类的类中,因此我尝试重写 Dispose 方法,但我无法使用 DisposeValue,因为它被声明为私有。
如何添加新的 Dispose 语句?
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not disposedValue Then
If disposing Then
''# ...
End If
End If
disposedValue = True
End Sub
提前致谢!
扩展信息:我认为我应该在继承者的基类中实现相同的逻辑。我说得对吗?
更多信息:当您声明一个类实现 IDisposable 时,我正在使用 Vb.Net 自动编写的片段。
I must add some Dispose code to a class that inherits from a class that already implements IDisposable so I tried to do an Override of the Dispose method but I have not available the disposedValue because it is declared as private.
How can I add the new Dispose statements?
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not disposedValue Then
If disposing Then
''# ...
End If
End If
disposedValue = True
End Sub
Thanks in advance!
EXTENDED INFO: I think that I should implement the same logic present at the base class at the inheritor. Am I right?
MORE INFO: I am using the snipet that Vb.Net automatically writes when you declare that a class implements IDisposable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在派生类中创建一个单独的
disposeValue
字段。但是,您可能应该将其命名为
isDispose
。请注意,如果您调用
Dispose
两次,FCL 中的所有类都不会执行任何操作,因此多次删除该逻辑并进行处置不一定有任何问题。显然,这取决于您在 Dispose 中执行的操作;你应该检查一下。确保调用
MyBase.Dispose(diswriting)
。You could make a separate
disposedValue
field in the derived class.However, you should probably name it
isDisposed
.Note that all classes in the FCL will not do anything if you call
Dispose
twice, so there isn't necessarily anything wrong with taking out that logic and disposing multiple times. Obviously, this depends on what you're doing inDispose
; you should check.Make sure to call
MyBase.Dispose(disposing)
.不要尝试复制基类逻辑,而是调用 MyBase.Dispose(disusing)。
Instead of trying to duplicate the base class logic, call MyBase.Dispose(disposing).
好吧,事实上它是私有的而不是受保护的,这可能意味着你不应该这样做。但如果你坚持的话,你可以使用反射。是的,这可能是最糟糕的方法:
Well, the fact that it is private instead of protected probably means you aren't supposed to do that. But if you insist, you could use reflection. Yeah, this is probably the worst possible way to do it: