我在创建可以动态创建变量类型对象的子项时遇到问题。这是我想要实现的一个例子:
class systemSettings
'some properties
end class
Class fireSystemSettings
inherits systemSettings
'some additional properties
end class
Class windSystemSettings
inherits systemSettings
'some additional properties
end class
sub createSystem(systemType as Type, arg1 as object, arg2 as object)
Dim newSystem as New systemType(arg1, arg2)
systemCollection.add(newSystem)
end sub
我无法让它发挥作用。我做了很多研究,看过泛型类型,反射和其他工具,但我无法确定如何最好地解决这个问题。
答案 0 :(得分:8)
您正在寻找Activator.CreateInstance(systemType)
答案 1 :(得分:3)
使用泛型:
Sub createSystem(Of T As {New, systemSettings})()
Dim newSystem As New T
systemCollection.add(newSystem)
End Sub
并将其命名为:
createSystem(Of windSystem)
解释:
术语Of T
允许您创建可用于任何类型的方法。每次调用T的新值时,都会在内存中创建一个新方法。
术语As {New, systemSettings}
约束T
。它表示T必须表示来自systemSettings
的类型。它还说T
必须包含一个默认构造函数:New()
,这是命令New T
所必需的。请注意,您不能将更精细的构造函数指定为泛型约束。
如果在构造函数中需要参数,则可以在基类中创建Initialise
方法。由于T
被约束为systemSettings
,因此可以保证Initialise
方法存在。
Class systemSettings
Public Overridable Sub Initialise(arg1 As Object, arg2 As Object)
'initialise properties
End Sub
'some properties
End class
Class fireSystemSettings
Inherits systemSettings
Public Overrides Sub Initialise(arg1 As Object, arg2 As Object)
'initialise properties
End Sub
'some additional properties
End Class
Class windSystemSettings
Inherits systemSettings
Public Overrides Sub Initialise(arg1 As Object, arg2 As Object)
'initialise properties
End Sub
'some additional properties
End Class
Sub createSystem(Of T As {New, systemSettings})(arg1 As Object, arg2 As Object)
Dim newSystem As New T
newSystem.Initialise(arg1, arg2)
systemCollection.add(newSystem)
End Sub