2010-11-12 95 views
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和例題可能有不同的特性,這是我需要設置...

這是可行的?

回答

4

您可以使用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的東西,我不知道)。

+0

也許是一個愚蠢的問題,但我將如何設置實例的屬性,而不是鑄造它? (因爲我不知道要投什麼) – tardomatic 2010-11-12 12:17:59

+0

@ tardomatic:優秀的問題;我正在編輯這個答案,因爲你提出了它:) – 2010-11-12 12:18:35

+1

小改進:'不...是Nothing' =>'... IsNot Nothing'。 - 'CType' =>'DirectCast'(在這種情況下)。 – 2010-11-12 12:20:55

相關問題