在列表中处理 Child 类
Disposing of Child Classes inside Lists
我有一个代表一组文件的容器class。有 10 种不同类型的文件,每种文件类型有 24 小时文件。我为每种文件类型创建了一个子 class,以及一个 24 小时制子 class 的列表,因此总共有 240 个 class。
当我用完容器 class 后,我想处理掉它,但是我需要处理所有单独的 class 实例吗?这是我在 Container class dispose 方法上的代码,但我不知道如何在所有子 classes 上调用 dispose 方法。我相信我需要这个的原因是因为随着我的项目的增长,我可能不得不添加更多 classes 和列表。感谢您的帮助!!
Public Sub Dispose() Implements IDisposable.Dispose
Dim objType As Type = Me.[GetType]()
Dim properties As PropertyInfo() = objType.GetProperties()
For Each [property] As PropertyInfo In properties
Dim tColl As Type = GetType(ICollection(Of ))
Dim t As Type = [property].PropertyType
Dim name As String = [property].Name
'check for collection
If t.IsGenericType AndAlso tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) OrElse t.GetInterfaces().Any(Function(x) x.IsGenericType AndAlso x.GetGenericTypeDefinition() = tColl) Then
Dim listObject As IEnumerable = DirectCast([property].GetValue(Me, Nothing), IEnumerable)
If listObject IsNot Nothing Then
Dim enumerable = TryCast(listObject, IEnumerable(Of Object))
Dim list = enumerable.ToList()
For i = 0 To list.Count - 1
'dispose of child classes, like list.item(i).dispose
Next
End If
End If
Next
GC.SuppressFinalize(Me)
End Sub
如果您确实想要明确处置它们,您可以使用与创建它们相同的方法来完成(一旦您完成了它们)。不必在父对象中完成。
我有一个代表一组文件的容器class。有 10 种不同类型的文件,每种文件类型有 24 小时文件。我为每种文件类型创建了一个子 class,以及一个 24 小时制子 class 的列表,因此总共有 240 个 class。
当我用完容器 class 后,我想处理掉它,但是我需要处理所有单独的 class 实例吗?这是我在 Container class dispose 方法上的代码,但我不知道如何在所有子 classes 上调用 dispose 方法。我相信我需要这个的原因是因为随着我的项目的增长,我可能不得不添加更多 classes 和列表。感谢您的帮助!!
Public Sub Dispose() Implements IDisposable.Dispose
Dim objType As Type = Me.[GetType]()
Dim properties As PropertyInfo() = objType.GetProperties()
For Each [property] As PropertyInfo In properties
Dim tColl As Type = GetType(ICollection(Of ))
Dim t As Type = [property].PropertyType
Dim name As String = [property].Name
'check for collection
If t.IsGenericType AndAlso tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) OrElse t.GetInterfaces().Any(Function(x) x.IsGenericType AndAlso x.GetGenericTypeDefinition() = tColl) Then
Dim listObject As IEnumerable = DirectCast([property].GetValue(Me, Nothing), IEnumerable)
If listObject IsNot Nothing Then
Dim enumerable = TryCast(listObject, IEnumerable(Of Object))
Dim list = enumerable.ToList()
For i = 0 To list.Count - 1
'dispose of child classes, like list.item(i).dispose
Next
End If
End If
Next
GC.SuppressFinalize(Me)
End Sub
如果您确实想要明确处置它们,您可以使用与创建它们相同的方法来完成(一旦您完成了它们)。不必在父对象中完成。