1
我有一个包含多个类的类库。我想动态地创建其中一个类的实例,设置它的属性并调用一个方法。如何在将对象的名称作为字符串传递时动态创建对象的实例? (VB.NET)
例子:
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
例1和例题可能有不同的特性,这是我需要设置...
这是可行的?
也许是一个愚蠢的问题,但我将如何设置实例的属性,而不是铸造它? (因为我不知道要投什么) – tardomatic 2010-11-12 12:17:59
@ tardomatic:优秀的问题;我正在编辑这个答案,因为你提出了它:) – 2010-11-12 12:18:35
小改进:'不...是Nothing' =>'... IsNot Nothing'。 - 'CType' =>'DirectCast'(在这种情况下)。 – 2010-11-12 12:20:55