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