我有一个包含许多类的类库.我想动态创建这些类之一的实例,设置其属性,并调用方法.
例:
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
Run Code Online (Sandbox Code Playgroud)
所以,我想创建如下代码.
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
Run Code Online (Sandbox Code Playgroud)
Example1和Example2可能有不同的属性,我需要设置...
这可行吗?
你可以用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
Run Code Online (Sandbox Code Playgroud)
请注意,包含类型名称的字符串必须包含完整的类型名称,包括命名空间.
如果你需要访问类型上更专业的成员,你仍然需要转换它们(除非VB.NET已经包含类似于dynamicC#的东西,我不知道).