How do I dynamically create an instance of an object when passed the name of the object as a String? (VB.NET)
I have a class library that contains a number of classes. I would like to dynamically create an instance of one of these classes, set its properties, and call a method.
Example:
Public Interface IExample
Sub DoSomething()
End Interface
Public Class ExampleClass
Implements IExample
Dim _calculatedValue as Integer
Public Property calculatedValue() as Integer
Get
return _calculatedValue
End Get
Set(ByVal value As Integer)
_calculatedValue= value
End Set
End Property
Public Sub DoSomething() Implements IExample.DoSomething
_calculatedValue += 5
End Sub
End Class
Public Class Example2
Implements IExample
Dim _calculatedValue as Integer
Public Property calculatedValue() as Integer
Get
return _calculatedValue
End Get
Set(ByVal value As Integer)
_calculatedValu开发者_StackOverflowe = value
End Set
End Property
Public Sub DoSomething() Implements IExample.DoSomething
_calculatedValue += 7
End Sub
End Class
So, I want to then create code as follows.
Private Function DoStuff() as Integer
dim resultOfSomeProcess as String = "Example2"
dim instanceOfExampleObject as new !!!resultOfSomeProcess!!! <-- this is it
instanceOfExampleObject.calculatedValue = 6
instanceOfExampleObject.DoSomething()
return instanceOfExampleObject.calculatedValue
End Function
Example1 and Example2 may have different properties, which I need to set...
Is this doable?
You can use Activator.CreateInstance
for this. The easiest way (IMO) is to first create a Type
object and pass that to Activator.CreateInstance
:
Dim theType As Type = Type.GetType(theTypename)
If theType IsNot Nothing Then
Dim instance As IExample = DirectCast(Activator.CreateInstance(theType), IExample)
''# use instance
End If
Note though that the string containing the type name must contain the full type name, including the namespace.
If you need to access more specialized members on the types, you will still need to cast them (unless VB.NET has incorporated something similar to dynamic
in C#, which I am not aware of).
精彩评论