2015-05-30 30 views
4

我有一个表示一组文件的容器类。有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 
+3

集合类不应该显式地处理其中的对象。 GC通常会为我们做所有这些工作(来自MSDN:*垃圾收集器会在不再使用该对象时自动释放分配给管理对象的内存*)。如果这些类分配资源,那么*它们*应该实现'IDisposable'来根据需要进行清理。如果你运行CA,它会告诉你哪些类应该实现它。 – Plutonix

+0

感谢Plutonix。很高兴知道。 – JoeB

回答

0

如果您确实想要显式处理它们,您可以使用与创建它们相同的方法(一旦完成它们)来完成。父对象中没有被完成。