在列表中处置子类

时间:2015-05-30 04:52:39

标签: vb.net dispose

我有一个表示一组文件的容器类。每种类型的文件有10种不同类型的文件和24小时文件。我已经为每种文件类型创建了一个子类,以及一个24小时的子类列表,所以总共有240个类。

当我完成容器类时,我想处理它,但是我是否需要处理所有单独的类实例?这是我在Container类dispose方法上的代码,但我无法弄清楚如何在所有子类上调用dispose方法。我认为我需要这个的原因是因为随着项目的增长,我可能需要添加更多的类和列表。任何帮助表示赞赏!!

     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

1 个答案:

答案 0 :(得分:0)

如果你想明确处理它们,你可以用你创建它们的方法(一旦你完成它们)完成它。不必在父对象中完成。