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

后端 未结 4 756
感动是毒
感动是毒 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: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"))
    

提交回复
热议问题