5

(这也可以表述为“如何迭代从 C++/CX 中的 C# Windows 运行时组件返回的集合?”)

我尝试使用std::for_eachIIterable<T>得到以下编译时错误

错误 C2664: 'std::begin' : 无法将参数 1 从 'my_collection_type ^' 转换为 'Platform::String ^' 没有可用的用户定义转换运算符,或指向的类型不相关;转换需要 reinterpret_cast、C-style cast 或 function-style cast

如何迭代集合?

4

3 回答 3

10

这也应该有效

for (IIterator<T> iter = iterable->First(); iter->HasCurrent; iter->MoveNext())
{
   T item = iter->Current;
}
于 2013-05-27T00:13:46.930 回答
10

为此,您需要添加

#include "collection.h"

(和可选)

using namespace Windows::Foundation:Collections

到您的源文件。

然后,您可以按如下方式遍历集合

for_each (begin(my_collection), 
          end(my_collection), 
          [&](my_collection_type^ value) {
          // code goes here...
});

注意:您可能还需要using namespace std(对于for_each)。

于 2012-06-17T20:52:43.360 回答
4

在 C++/CX 中编写 Windows 运行时组件时,您可以使用类似 C# 的构造:

for each (auto item in collection)
{
    item->DoSomething();
}
于 2015-08-31T08:23:58.377 回答