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

后端 未结 4 737
感动是毒
感动是毒 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:40

    Here is a really easy way I have found while rummaging through the internet:

    dynamicControl = Activator.CreateInstance(Type.GetType("MYASSEMBLYNAME." + controlNameString))
    
    0 讨论(0)
  • 2020-12-06 19:45

    I'm pretty sure Activator is used for remoting. What you want to do is use reflection to get the constor and invoke it here's an example http://www.eggheadcafe.com/articles/20050717.asp

    EDIT: I was misguided about Activator until jwsample corrected me.

    I think the problem your having is that your assembly is the one that GetType is using to try and find Button. You need to call it from the right assembly.

    This should do it

    Dim asm As System.Reflection.Assembly = System.Reflection.Assembly.LoadWithPartialName("System.Windows.Forms")
    
    
    Dim obj As Object = Activator.CreateInstance(asm.GetType("System.Windows.Forms.Button"))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-06 19:52

    Take a look at the Activator.CreateInstance(Type) method.

    If your input is the name of a class you should be able do this:

    Dim obj As Object = Activator.CreateInstance(GetType("Name_Of_Your_Class")) 
    

    You'll have to fiddle with the GetType call to make sure you give it enough information but for most cases just the name of the class should work.

    0 讨论(0)
提交回复
热议问题