Reputation: 1833
I'm having trouble creating a sub that can create objects of a variable type on the fly. Here's an example of what I'm trying to achieve:
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
I can't get it to work. I've done a fair bit of research, and looked at generic types, reflection, and other tools, but I'm having trouble determining how best to tackle this problem.
Upvotes: 8
Views: 6771
Reputation: 12814
Use generics for this:
Sub createSystem(Of T As {New, systemSettings})()
Dim newSystem As New T
systemCollection.add(newSystem)
End Sub
And call it with:
createSystem(Of windSystem)
To explain:
The term Of T
lets you create a method that can be used for any type. Every time you call it for a new value of T, a new method is created in memory.
The term As {New, systemSettings}
constrains T
. It says that T must represent a type that is or derives from systemSettings
. It also says that T
must contain a default constructor: New()
which is required for the command New T
. Note that you cannot specify a more elaborate constructor as a generics constraint.
If you require parameters in your constructor, you can create an Initialise
method in the base class. Because T
is constrained to systemSettings
, it is guaranteed that the Initialise
method exists.
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
Upvotes: 4