gpt4 book ai didi

vba - 创建作为参数传递的类的副本

转载 作者:行者123 更新时间:2023-12-03 03:25:49 25 4
gpt4 key购买 nike

我正在VBA中创建一个项目来自动处理异步准多线程(拗口,抱歉)。这涉及创建和运行一个类的多个副本,该类实现某个接口(interface),并在异步任务完成时引发一些已知事件。接口(interface)类似于 this example

我的程序调用该类来执行其代码,并监听引发的事件,这一切都工作正常。现在,我的最终任务是获取实现适当接口(interface)的任何给定类,并制作多个副本以设置并行运行。

如何复制传递给例程的类?

如何获取类引用并创建多个版本?

或者在代码中,我的每个线程类(处理传递的异步类的类)将有一个 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

最佳答案

您需要检查可能的类型并采取相应的行动:

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

或者,您可以向接口(interface)添加工厂方法:

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()

关于vba - 创建作为参数传递的类的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com