经过几天的研究,我遇到了一个无法解决的问题...
我必须创建一个应用程序来读取 Excel 文件并根据列的名称和值生成对象以测试其他应用程序。这部分没有问题,我可以在不知道对象类型的情况下为对象创建和分配值。
我遇到的问题是其中一些对象之间有关系,因为对象 A 有一个列表(对象 B)。我可以识别这些。
我的对象是这样声明的:
Public Class Person
Public Property Name as String
Public Property Age as Integer
Public Property Dogs as List(Of Dog)
...
End Class
Public Class Dog
Public Property Name as String
...
End Class
当我调试时,我得到类似的东西: Person: Name = "Something", Age = 30, Dogs = Nothing
由于我的 List(Of T) 不等于任何内容,因此我需要在将对象添加到其中之前对其进行实例化。由于我还没有找到任何方法来告诉 List 实例化自身,因此我尝试为该属性分配一个 New List。
我有一些我试过的代码:
'In this case, unObjetParent would be a Person, and unObjetEnfant would be a Dog
Private Function AssocierObjets(ByRef unObjetParent As Object, ByRef unObjetEnfant As Object) As Boolean
Dim proprietes() As Reflection.PropertyInfo = unObjetParent.GetType.GetProperties
Dim typeEnfant As Type = unObjetEnfant.GetType
For Each p As Reflection.PropertyInfo In proprietes
If p.PropertyType.Name.Equals("List`1") Then
Dim type As Type = p.PropertyType
Dim splittedAssemblyQualifiedName As String() = type.AssemblyQualifiedName.Split(","c)
Dim typeOfList As Type = type.GetType(splittedAssemblyQualifiedName(0).Substring(splittedAssemblyQualifiedName(0).LastIndexOf("["c) + 1))
' ^ The way I found to get the Type of the GenericArgument of the List before instantiating it.
If typeOfList = typeEnfant Then
'This create a object with it's name, in this case, it returns a Dog
Dim prototype = DefinirObjet(typeOfList.Name)
'My first try, it returns a List(Of VB$AnonymousType_0`1[System.Object])
'which I can't convert into a List(Of Dog(for this example))
Dim prop = New With {unObjetEnfant}
Dim l = prop.CreateTypedList
p.SetValue(unObjetParent, l, Nothing)
'This one doesn't work either as it returns a List(Of Object)
'which I can't convert into a List(Of Dog(for this example))
p.SetValue(unObjetParent, CreateTypedList2(prototype), Nothing)
End If
End If
Next
Return True
End Function
<System.Runtime.CompilerServices.Extension()> _
Function CreateTypedList(Of T)(ByVal Prototype As T) As List(Of T)
Return New List(Of T)()
End Function
Private Function CreateTypedList2(Of T)(ByVal unPrototype As T) As List(Of T)
Return New List(Of T)
End Function
另外,我不能修改对象,因为我应该能够接受我们需要测试的任何对象库。
这可能吗?我需要解决这个问题。提前致谢
PS对不起,如果我的英语不好,那不是我的母语。