当对象的名称作为字符串传递时,如何动态创建对象的实例?(VB.NET)
我有一个包含许多类的类库。我想动态创建这些类之一的实例,设置其属性,并调用一个方法 例如:当对象的名称作为字符串传递时,如何动态创建对象的实例?(VB.NET),vb.net,Vb.net,我有一个包含许多类的类库。我想动态创建这些类之一的实例,设置其属性,并调用一个方法 例如: Public Interface IExample Sub DoSomething() End Interface Public Class ExampleClass Implements IExample Dim _calculatedValue as Integer Public Property calculatedValue() as Integer
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
私有函数DoStuff()为整数
将ResultToSomeProcess设置为String=“Example2”
dim instanceOfExampleObject作为新对象!!!结果某些过程 你可以用这个。最简单的方法(IMO)是首先创建类型
对象并将其传递给激活器。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
,我不知道这一点)。可能是一个愚蠢的问题,但是我如何在不强制转换的情况下设置实例的属性呢?(因为我不知道该怎么办)@tardomatic:问得好;当你提出答案时,我正在把它编辑成:)小的改进:不是……什么都不是
=>…不是什么都不是
CType
=>DirectCast
(在本例中)。@Konrad:谢谢!我离开VB.NET已经有一段时间了,有些东西显然已经消失了。我正在考虑某种“对象工厂”,它将返回我想要的类的实例,但这将再次使我无法更改对象的属性(以及一个相当大的case语句…)关于如何解决这类问题,还有其他想法吗?