将字典中的所有值转换为 C++/CLI 中的列表

Convert all values from dictionary into list in C++/CLI

我有一个字典,我想将其值转换为一个列表。在 C# 中,我会使用这种方法:

var dict = new Dictionary<int, int>();
var list = dict.Values.ToList();

所以我想在 C++/CLI 中做同样的事情:

auto dict = gcnew Dictionary<int, int>();
auto list = dict->Values->ToList(); // error C2039

但这不起作用,因为错误:

Error   C2039   
'ToList': is not a member of 'System::Collections::Generic::Dictionary<int,int>::ValueCollection'   

我不知道,我做错了什么,我是 C++/CLI 的新手。

最小可重现示例:

#using "System.Linq.dll"

using namespace System::Collections::Generic;
using namespace System::Linq;

int main()
{
    auto dict = gcnew Dictionary<int, int>();
    auto list = dict->Values->ToList();
}

编译:

cl /clr test.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27035
for Microsoft (R) .NET Framework version 4.08.4121.0
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
test.cpp(10): error C2039: 'ToList': is not a member of 'System::Collections::Generic::Dictionary<int,int>::ValueCollection'

C++ CLI does not support calling extension methods as members of target type:

targetType.ExtensionMethod(args);

您应该将 ToList() 作为常规静态方法调用:

Linq::Enumerable::ToList(list);