将C++/cli类指定为Dictionary中的TValue类型的正确语法是什么

1 dictionary c++-cli

当我尝试将c ++/cli值结构定义为字典中的TValue时,我在c ++/cli中的语法有问题

我这样做是因为我想在本机类指针和system :: String(以String作为键)之间维护一个映射,因此将本机指针包装在一个struct中.

value struct MyStruct
{
   NativeClass *m_p;
}

Dictionary<System::String ^, MyStruct> MyMap;

NativeClass* FindLigandModelMap(System::String ^file)
{
   MyStruct m;
   if (m_LigandToModelMap.TryGetValue(file, %m)) <--- ERROR HERE
      return(m.m_p);
   return(NULL);
}
Run Code Online (Sandbox Code Playgroud)

Thi给出了编译器错误:错误C2664:'System :: Collections :: Generic :: Dictionary :: TryGetValue':无法将参数2从'MyStruct ^'转换为'MyStruct%'

我尝试了MyStruct的各种声明但没有成功.

Han*_*ant 7

您的代码段中有许多细微的语法错误,您可以从C++/CLI入门中受益:

  1. 值类型声明需要分号.C++规则
  2. Dictionary <>是一个引用类型,需要帽子.C++/CLI规则
  3. 声明暗示通过引用传递参数,不要使用%.C++规则
  4. NULL在托管代码中无效,您必须使用nullptr.C++/CLI规则

从而:

#include "stdafx.h"
#pragma managed(push, off)
class NativeClass {};
#pragma managed(pop)

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

value struct MyStruct
{
    NativeClass *m_p;
};   // <== 1

ref class Example {
public:
    Dictionary<System::String ^, MyStruct>^ MyMap;   // <== 2

    NativeClass* FindLigandModelMap(System::String ^file)
    {
        MyStruct m;
        if (MyMap->TryGetValue(file, m))  // <== 3
            return(m.m_p);
        return nullptr;  // <== 4
    }
    // etc...
};
Run Code Online (Sandbox Code Playgroud)