2017-04-13 107 views
0

假定以下示例类其模拟从XSD文件生成的类的类型:在不调用构造函数的情况下递归地实例化子类?

Public Class MyClass 
    Public Class MyInnerClass1 
     Public Class MyInnerInnerClass1 
      Public Property MyProp1 as string 
      Public Property MyProp2 as string 
      ... 
     End Class 
     ... 
     Public Property MyInnerInnerClassProp1 as MyInnerInnerClass1 
    End Class 

    Public property MyInnerClassProp1 as MyInnerClass1 
    Public property MyInnerClassProp2 as MyInnerClass2 
    ... 
End Class 

注意,没有构造函数。在触及基本属性(如Property MyProp1 as string)之前,内部类的级别(在此特定情况下)可能会循环深入5个级别。

如何递归遍历所有公共可写属性,并将它们初始化为没有构造函数的对象类型的新实例?

例如,这里是我现在的代码,目前只能深入一层。

Private Shared Sub InitProperties(obj As Object) 
    For Each prop As Object In obj.[GetType]().GetProperties(BindingFlags.[Public] Or BindingFlags.Instance).Where(Function(p) p.CanWrite) 
     Dim type__1 = prop.PropertyType 
     Dim constr = type__1.GetConstructor(Type.EmptyTypes) 
     'find paramless const 
     If type__1.IsClass Then 
      Dim propertyInstance = DirectCast(FormatterServices.GetUninitializedObject(type__1.GetType()), Object) 

      'Dim propInst = Activator.CreateInstance(type__1) 
      'prop.SetValue(obj, propInst, Nothing) 
      InitProperties(propertyInstance) 
     End If 
    Next 
End Sub 

回答

0

我对你的代码做了一些小的修改,以使它适用于你提供的示例类。 (虽然我确实将字符串属性更改为Integer以避免出现一个错误。)我还添加了一个用于限制递归调用数的参数,并且在初始化它之前检查属性是否等于Nothing。 (如果您在静态类之间有循环引用,则此检查仅起作用。)

Private Shared Sub InitProperties(obj As Object, Optional ByVal depth As Integer = 5) 
    For Each prop As PropertyInfo In obj.GetType().GetProperties(BindingFlags.Public Or BindingFlags.Instance).Where(Function(p) p.CanWrite) 
     Dim type__1 As Type = prop.PropertyType 

     If type__1.IsClass And IsNothing(prop.GetValue(obj, Nothing)) And depth > 0 Then 
      Dim propertyInstance As Object = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type__1) 
      prop.SetValue(obj, propertyInstance, Nothing) 
      InitProperties(propertyInstance, depth - 1) 
     End If 
    Next 
End Sub 
相关问题