使用类的文本名称创建一个新对象 [英] Create a new object using the text name of the class
问题描述
是否可以通过使用类的文本名称将对象设置为类的新实例?
Is there a way to set an object to the new instance of a class by using the text name of the class?
我将拥有一个类库,根据其他变量,我想在运行时获取这些类之一.
I will have a library of classes, and depending on some other variable, I want to get one of these classes at runtime.
例如我有"CTest1","CTest2","CTest3"
E.g. I have "CTest1", "CTest2", "CTest3"
我将具有与以下类似的功能
I would have function similar to the below
Function GetTestClass(lngClassNo as long) as Object
Dim strClassName as String
strClassName = "CTest" & CStr(lngClassNo)
Set GetTestClass = New instance of class(strClassName)
End Function
推荐答案
VBA中没有任何反映,因此我认为这是不可能的.恐怕您必须执行以下操作:
There's no reflection in VBA, so I don't think this is possible. You'd have to do something like the following I'm afraid:
Function GetTestClass(lngClassNo as long) as Object
Select Case lngClassNo
Case 1
Set GetTestClass = New CTest1
Case 2
Set GetTestClass = New CTest2
...
End Select
End Function
除非您的CTest类是在COM DLL中定义的,否则可以使用CreateObject语句.但是,您将需要使用VB6创建这样的DLL,而不能在Excel,Access等中创建DLL.
Unless that is your CTest classes are defined in a COM DLL, in which case you could use the CreateObject statement. You would need to use VB6 to create such a DLL though, you can't create DLLs in Excel, Access, etc.
Function GetTestClass(lngClassNo as long) as Object
Set GetTestClass = CreateObject("MyDll.CTest" & lngClassNo)
End Function
这篇关于使用类的文本名称创建一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!