加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

vb.net – Visual Basic:使用字符串作为名称动态创建对象

发布时间:2020-12-17 00:02:15 所属栏目:大数据 来源:网络整理
导读:有没有办法使用字符串作为类名动态创建对象? 我已经离开VB好几年了,但是为了解决另一种语言的问题,我不得不在这个中开发一个包装器.我有一个工厂方法,可以根据其他地方的输入动态创建和返回一个类型的对象.提供的输入是从中创建对象的类名.正常语法意味着必
有没有办法使用字符串作为类名动态创建对象?

我已经离开VB好几年了,但是为了解决另一种语言的问题,我不得不在这个中开发一个包装器.我有一个工厂方法,可以根据其他地方的输入动态创建和返回一个类型的对象.提供的输入是从中创建对象的类名.正常语法意味着必须明确拼写整个类.要做到这一点,实际上可能有数百个if / then或者case来处理引用的libs中所有可用的类/对象选择:

If c_name = "Button" then obj = new System.Windows.Forms.Button
If c_name = "Form" then obj = new System.Windows.Forms.Form
....

我希望将所有这些案例处理减少到一行:IE …

my_class_name = "whateverclass"
obj = new System.Windows.Forms.my_class_name()

在PHP中,这样处理就像……

$my_class_name = "whateverclass";
$obj = new $my_class_name();

编辑:看看一些答案,我想我在这里已经超出了我的想法.尽管我对this variation giving more options更感兴趣,包括提供构造参数,但我确实设法使用了Assembly类的this CreateInstance方法变体.

my_type_name = "System.Windows.Forms.Button"
asmb_name = "System.Windows.Forms,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"
button1 = Reflection.Assembly.Load(asmb_name).CreateInstance(my_type_name)

换句话说,它需要一种方法来做到这一点,而不是任何固有的语言语法?当使用完整的汇编字符串和类路径时,This Activator variation也工作.我怀疑CreateInstance可能没有完全的能力让我像对待它们一样正常对待对象,即obj = new System.Windows.Forms.Button.这就是为什么我不能简单地使用CreateObject.如果没有允许您用类名替换字符串的自然语言功能,那么是否有人能够了解使用CreateInstance可以获得哪些限制?

另外,基本的Activator.CreateInstance(在Unwrap之后)和Assembly.CreateInstance方法之间是否存在差异?

这可能会做你想要/测试的工作;在顶部切换类型注释以查看.
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读