Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当对象的名称作为字符串传递时,如何动态创建对象的实例?(VB.NET)_Vb.net - Fatal编程技术网

当对象的名称作为字符串传递时,如何动态创建对象的实例?(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语句…)关于如何解决这类问题,还有其他想法吗?