如何重写 Dispose 方法并将 dippedValue 设为 Private?

发布于 2024-08-18 00:24:20 字数 465 浏览 6 评论 0原文

我必须将一些 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 技术交流群。

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

发布评论

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

评论(3

眼前雾蒙蒙 2024-08-25 00:24:20

您可以在派生类中创建一个单独的 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 in Dispose; you should check.

Make sure to call MyBase.Dispose(disposing).

友欢 2024-08-25 00:24:20

不要尝试复制基类逻辑,而是调用 MyBase.Dispose(disusing)。

Instead of trying to duplicate the base class logic, call MyBase.Dispose(disposing).

娜些时光,永不杰束 2024-08-25 00:24:20

好吧,事实上它是私有的而不是受保护的,这可能意味着你不应该这样做。但如果你坚持的话,你可以使用反射。是的,这可能是最糟糕的方法:

//(System.Reflection.BindingFlags...)
this.GetType().GetField("_privateVarName", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);

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:

//(System.Reflection.BindingFlags...)
this.GetType().GetField("_privateVarName", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文