如何在 VBA 中实现自定义可迭代类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20194919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:38:29  来源:igfitidea点击:

How to implement custom iterable class in VBA

excelclassvbaforeachiunknown

提问by JayC667

I want to add a feature to my classes so I can use them in for-each loops.

我想向我的类添加一个功能,以便我可以在 for-each 循环中使用它们。

I wrote hashmaps, arraylists, queues, sets and so on that I want to iterate over. Now I'm looking for a way to implement the IUnknown class to build custom iterators.

我写了哈希图、数组列表、队列、集合等等,我想迭代它们。现在我正在寻找一种方法来实现 IUnknown 类来构建自定义迭代器。

I already know how to use

我已经知道怎么用了

private objPeople as Collection
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40"
    Set NewEnum = objPeople.[_NewEnum]
End Property

but all those examples out there are based on the Collection class, which I do not want to use.

但是所有这些示例都基于我不想使用的 Collection 类。

What I want to focus on is trying to implement the IUnknown interface, but I haven't found any references on how to do that.

我想要关注的是尝试实现 IUnknown 接口,但我还没有找到任何关于如何做到这一点的参考。

I have vast experience in Java, C++, C# and so on, so I assume that THERE HAS TO BE A WAY to implement that even in VBA, maybe even with API calls stuff like that.

我在 Java、C++、C# 等方面拥有丰富的经验,所以我认为即使在 VBA 中也必须有一种方法来实现它,甚至可能使用 API 调用之类的东西。

采纳答案by Tomasz

The answer is that it can be done, but it is ugly (requires and IDL, two .BASmodules and two .clsmodules (one of which is your Collection Class module). For full information see this link:

答案是可以做到,但是很丑(需要 and IDL,两个.BAS模块和两个.cls模块(其中一个是你的 Collection Class 模块)。有关完整信息,请参阅此链接:

Create Your Own "Super Collections" in VB

在 VB 中创建您自己的“超级收藏”

Good luck! It seemed to complicated for what I needed to do, so for now I just iterate over the Collection object enumerator.

祝你好运!我需要做的事情似乎很复杂,所以现在我只是遍历 Collection 对象枚举器。

回答by RubberDuck

The long and short of it is you can't implement IUnknown. The same goes for Collection. They're both Com objects that are unavailable for extension in VBA. You can create custom collectionsand do other very cool iterable thingsthough.

总而言之,您无法实现 IUnknown。这同样适用于集合。它们都是在 VBA 中不可扩展的 Com 对象。您可以创建自定义集合并执行其他非常酷的可迭代操作