微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

有没有办法使用字符串作为类名动态创建对象?

我已经离开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

原文地址:https://www.jb51.cc/vb/255920.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐