如何通过从字符串变量获取类的名称来实例化该类? [英] How to instantiate the class by getting the name of the class from string variable ?
问题描述
我有一个接口和一些实现该接口的类。实际上,类是具有不同实现的客户端。我必须从数据库中检查客户端名称,根据这些客户端名称,它们各自的类将实例化并且将起作用。假设我得到的客户端名称如
昏暗的客户端作为新的clientConfiguration
client.Name =abc
我已经有一个实现接口的同名类,现在在运行时我希望在client.Name的帮助下实例化该类。
是否可以这样做。
谢谢,
Saad汗
I have an interface and some classes implementing that interface. Actually classes are the clients which have their different implementations. I have to check the client name from database on the basis of which their respective class will instantiate and will work. Suppose i am getting the client name like
dim client as new clientConfiguration
client.Name = "abc"
I already have a class with the same name implementing an interface and now at the run time i want to instantiate that class with the help of client.Name.
Is it possible to do so.
Thanks,
Saad Khan
推荐答案
这是可能的。您将使用反射。
尝试 http://social.msdn.microsoft.com/Forums/vstudio/en-US/4d915685-a728-42d9-99e0-02e16dc159d1/reflection-instantiate-class-via- a-string [ ^ ]。
It is possible. You will use reflection.
Try http://social.msdn.microsoft.com/Forums/vstudio/en-US/4d915685-a728-42d9-99e0-02e16dc159d1/reflection-instantiate-class-via-a-string[^].
你需要反思:
You need reflection:
Dim t As Type = Type.GetType("MyNameSpace.Form1")
Dim o As Object = Activator.CreateInstance(t)
Dim f As Form = TryCast(o, Form)
If Not f Is Nothing Then
f.Show()
End If
这篇关于如何通过从字符串变量获取类的名称来实例化该类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!