2010-11-12 93 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

相关问题