我有一个包含许多类的类库。我想动态创建其中一个类的实例,设置其属性,并调用方法。
示例:
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)
_calculatedValue = value
End Set
End Property
Public Sub DoSomething() Implements IExample.DoSomething
_calculatedValue += 7
End Sub
End Class
所以,我想创建如下代码。
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和Example2可能有不同的属性,我需要设置...
这可行吗?
答案 0 :(得分:5)
您可以使用Activator.CreateInstance
。最简单的方法(IMO)是首先创建一个Type
对象并将其传递给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
请注意,包含类型名称的字符串必须包含完整的类型名称,包括命名空间。
如果你需要访问类型上更专业的成员,你仍然需要强制转换它们(除非VB.NET在C#中加入类似于dynamic
的东西,我不知道)。