在 Sub New() 上使用 CCW 的构造函数
我正在尝试为我的 VBA 项目创建一个 COM 类库,而我似乎偶然发现的限制之一是在 New() 子例程上使用构造函数。创建新的 COM 类后,将创建一个包含以下注释的 Public Sub New()
' 可创建的 COM 类必须有一个 Public Sub New() ' 不带参数,否则该类不会 ' 已在 COM 注册表中注册且无法创建 ' 通过 CreateObject.
显然,我想使用 new 关键字创建更多允许不同参数的子例程。但是,当我尝试执行此操作并在 VBA 中实现对象时,在尝试输入“预期语句结束”参数时出现错误。如果有人有任何信息,将不胜感激。
谢谢。
I'm trying to create a COM Class Library for my VBA Project and one of the limitations I've seemed to have stumbled across is using constructors on the New() subroutine. After creating the new COM class a Public Sub New() is created with the following comments
' A creatable COM class must have a Public Sub New() ' with no parameters, otherwise, the class will not be ' registered in the COM registry and cannot be created ' via CreateObject.
Obviously though I want to create more subroutines with the new keyword that allow for different parameters. However, when I try to do this and implement the objects in VBA I get an error when trying to input the parameters saying "End of statement expected". If anyone has any information that would greatly be appreciated.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有暴露给 COM 的类都必须有一个无参数构造函数 - 句点。原因是,当客户端实例化一个类时,调用最终会进入
CoCreateInstance()
全局函数(或几乎相同的IClassFactory::CreateInstance()
)。CoCreateInstance()
(或IClassFactory::CreateInstance()
)无法将参数传递到类的构造函数中,因此该类必须有一个无参数构造函数 - 该构造函数将用于在内部实例化该类。如果您需要的不仅仅是无参数构造函数 - 请使用工厂类。伪代码:
这样你就有了一个带有无参数构造函数的工厂类。您实例化工厂,然后调用其创建者方法来实例化您的类。
All classes exposed to COM must have a parameterless constructor - period. The reason is that when the client instantiates a class the call eventually goes into
CoCreateInstance()
global function (orIClassFactory::CreateInstance()
which is almost the same).CoCreateInstance()
(orIClassFactory::CreateInstance()
) have no means for passing parameters into the constructor of the class so that class must have a paremeterless constructor - that constructor will be used to instantiate the class internally.If you need more than a paremeterless constructor - use a factory class. Pseudocode:
this way you have a factory class with a paremeterless constructor. You instantiate the factory and then call its creator method for instantiating your class.