我正在VBA中创建一个项目来自动处理异步准多线程(满口,抱歉)。这围绕创建和运行Implements
某个接口的类的多个副本,并在异步任务完成时引发一些已知事件。接口类似于this example
我的程序调用类来执行它的代码,并监听引发的事件,这一切都正常。现在我的最后一项任务是获取Implements
适当接口的任何给定类,并使多个副本设置为并行运行。
如何制作传递给例程的类的副本?
如何获取课程参考并制作多个New
版本?
或者在代码中,我的每个线程类(处理传递的异步类的类)都有一个Worker
属性来保存它们的任务。
Private workerObject As IWorker
Public Property Set Worker(workObj As IWorker) 'pass unknown class with IWorker interface
'What goes here?
Set workerObject = workObj
'This won't work as then every thread points to the same worker
'I want something to create a New one, like
Set workerObject = New ClassOf(workObj)
'But of course that doesn't work
End Property
答案 0 :(得分:2)
您需要检查可能的类型并采取相应措施:
Dim workerObject As IWorker
If TypeOf workObj Is ImplementingClass1 Then
Set workerObject = New ImplementingClass1
ElseIf TypeOf workObj Is ImplementingClass2 Then
Set workerObject = New ImplementingClass2
End If
或者,您可以在界面中添加工厂方法:
Public Function CreateNew() As IWorker: End Function
在课程中实施:
Public Function IWorker_CreateNew() As IWorker
Set IWorker_CreateNew = New ImplementingClass1
End Function
然后:
Set workerObject = workObj.IWorker_CreateNew()