我遇到了一个问题,我需要使用反射将一个类加载到我的代码中,创建该类的数组,然后将该数组分配给另一个反射对象的属性。
我的最小例子是:
我的DLL:
Public Class MyItem
Public Property Id As Int32
End Class
Public Class MyMainItem
Public Property MyItems As MyItem()
End Class
我的测试应用程序:
Sub Main()
Dim myAssembly As Assembly = Assembly.LoadFile("c:\temp\MyDll.dll")
Dim myMainObject As Object = Activator.CreateInstance(myAssembly.GetType("MyDll.MyMainItem"))
Dim myItemArray(1) As Object
myItemArray(0) = Activator.CreateInstance(myAssembly.GetType("MyDll.MyItem"))
myItemArray(1) = Activator.CreateInstance(myAssembly.GetType("MyDll.MyItem"))
myMainObject.MyItems = myItemArray
End Sub
将myItemArray分配给MyItems时,我收到的错误是InvalidCastException:
Conversion from type 'Object()' to type 'MyItem()' is not valid.
有没有办法让myItemArray被理解为MyItem而不是Object的数组?