为什么我在 IDisposable 类中获得带有私有成员 IDisposable 的 CA2000?
我有一个实现 IDisposable 的类,因为它有一个 IDisposable 的私有成员字段“foo”(在构造函数中初始化)。我意外地收到 CA2000 代码分析错误,这要求我务必处理 foo.但是,我的类的 Dispose() 代码中有 foo.Dispose() ,它应该可以解决这个问题。
我做了一些搜索,令人惊讶的是找不到答案。我做错了什么?显然我错过了一些基本的东西。我该如何编写代码来克服这个问题?
我的VB代码:
Public Class Bar
Implements IDisposable
Private Foo As SomeDisposableThing
Public Sub New()
Foo = New SomeDisposableThing() With {.name = "hello"}
End Sub
'''' snip ''''
Private disposedValue As Boolean = False ' To detect redundant calls '
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
If Foo IsNot Nothing Then Foo.Dispose()
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class
I have a class that implements IDisposable because it has a private member field "foo" that is IDisposable (which is initialized in the constructor). I am unexpectedly getting a CA2000 Code Analysis error, which wants me to be sure to dispose of foo. However, I have foo.Dispose() in my class's Dispose() code, which should take care of this.
I did some searching around and surprisingly can't find an answer. What am I doing wrong? Clearly I missing something basic. How do I write my code to overcome this?
My VB code:
Public Class Bar
Implements IDisposable
Private Foo As SomeDisposableThing
Public Sub New()
Foo = New SomeDisposableThing() With {.name = "hello"}
End Sub
'''' snip ''''
Private disposedValue As Boolean = False ' To detect redundant calls '
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
If Foo IsNot Nothing Then Foo.Dispose()
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CA2000 错误并不是指实现了 IDisposable 的容器,而是指使用了未正确处理的本地容器。原因是您在一次性对象上使用对象初始值设定项。将生成的实际代码基本上如下所示。
此代码被 FxCop 正确标记为未在所有实例中正确处置
IDisposable
(temp. Name = "hello"
行在这种情况下不会被处理)。修复方法是不在这里使用对象初始值设定项并直接初始化
Foo
The CA2000 error doesn't refer to the container implementing
IDisposable
but rather the use of a local which is not properly disposed. The reason why is that you are using an object initializer on the disposable object. The actual code that will get generated is essentially the followingThis code is correctly flagged by FxCop as not properly disposing of an
IDisposable
in all instances (it's possible for an exception to occur on thetemp.Name = "hello"
line in which case it wouldn't be disposed).The fix is to not use an object initializer here and initialize
Foo
directly