Visual Basic: dynamically create objects using a string as the name

后端 未结 4 760
感动是毒
感动是毒 2020-12-06 19:25

Is there a way to dynamically create an object using a string as the class name?

I\'ve been off VB for several years now, but to solve a problem in another language,

4条回答
  •  一个人的身影
    2020-12-06 19:46

    This will likely do what you want / tested working; switch the type comment at the top to see.

    Imports System.Reflection
    
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '            Dim fullyQualifiedClassName as String = "System.Windows.Forms.TextBox"
        Dim fullyQualifiedClassName As String = "System.Windows.Forms.Button"
        Dim o = fetchInstance(fullyQualifiedClassName)
        ' sometime later where you can narrow down the type or interface...
        Dim b = CType(o, Control)
        b.Text = "test"
        b.Top = 10
        b.Left = 10
        Controls.Add(b)
    End Sub
    
    Private Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
        Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
        Dim o As Object = Nothing
        Try
            For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                If (ay.Name = nspc) Then
                    o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
                    Exit For
                End If
            Next
        Catch
        End Try
        Return o
    End Function
    

提交回复
热议问题