从字符串类名创建实例 [英] Create instance from string class name

查看:26
本文介绍了从字符串类名创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点?我有一个通过查询字符串传递的类名,我想基于它创建一个新实例.

Is there a way to achieve this? I have a class name that I pass via query string and I want to make a new instance based on that.

我尝试过的:

Private Function Carregar() As Object
    Dim bal = String.Concat("PROTBAL.", Request.QueryString("nomeBAL"))
    Dim ent = Request.QueryString("nomeENT")
    Dim codigo = Request.QueryString("codigo")
    Dim descricao = Request.QueryString("descricao")
    Dim teste = Activator.CreateInstance(Type.GetType(bal))
    Return teste.Listar()
End Function

事情是变量teste总是Nothing.

推荐答案

假设您正确连接类名,这应该有效:

assuming you concat the class name correctly, this should work:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(bal)

编辑

如果类型(类)可以/可能在另一个程序集中,那么这有效:

If the type (class) can/may be in another assembly, then this works:

System.Reflection.Assembly.GetAssembly(bal).CreateInstance(bal)

但我不确定这会起作用 eitehr - 我没有注意到名称中的点运算符 - 这是内部类还是命名空间引用?我不认为你可以这样解决内部类.如果你可以在 PROTBAL 上创建一个像 CreateNewThing 这样的方法,你可以去掉所有这些,只用一个 arg 调用该方法来指示你想要的类型(因为 PROTBAL 是已知的).

but I am not sure that will work eitehr - I did not notice the dot operator in the name - is this an internal class or namespace ref? I dont think you can resolve internal classes that way. If you could create a method on PROTBAL like CreateNewThing you could do away with all this and just call the method with an arg to indicate which type you want (since PROTBAL is known).

这篇关于从字符串类名创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆