C++ cli 无法将C#enum强制转换为C++;枚举位于第三个程序集中时的枚举

C++ cli 无法将C#enum强制转换为C++;枚举位于第三个程序集中时的枚举,c++-cli,C++ Cli,我有一个C级: 哪个使用C#enum 这由C++/CLI包装类和枚举访问: enum NativeEnum { Enum1, Enum2 }; class WrapperClass { public: WrapperClass(ManagedNamespace::MyManagedClass^ inManaged): _Managed(inManaged) {} NativeEnum GetEnumValue() { return (NativeEnu

我有一个C级:

哪个使用C#enum

这由C++/CLI包装类和枚举访问:

enum NativeEnum
{
  Enum1,
  Enum2
};

class WrapperClass
{
public:
  WrapperClass(ManagedNamespace::MyManagedClass^ inManaged):
    _Managed(inManaged)
  {}

  NativeEnum GetEnumValue()
  {
    return (NativeEnum)_Managed->EnumValue;
  }

private:
    gcroot<ManagedNamespace::MyManagedClass^> _Managed;
};

尝试派生基础值,然后强制转换为本机枚举

这是一种粗糙的方法,但在您的情况下可能已经足够了

NativeEnum someMethod(ManagedEnum myEnum)
{
  return (NativeEnum)(int)myEnum;
}

另一种方法是创建一个本机模板方法,同时接受类型和托管枚举输入,并返回本机类型。在这种情况下,您必须使用反射来确定托管枚举的基础类型。

< P>在尝试Aaron P的答案时,我发现问题是,我的C++项目中没有以它的枚举作为引用的C.C汇编。一旦我添加了参考资料,一切都很好。

这并不能回答这个问题。若要评论或要求作者澄清,请在他们的帖子下方留下评论-你可以随时对自己的帖子发表评论,一旦你有足够的评论,你就可以发表评论。对不起,我是新来这里发帖的,在你发表评论时正在编辑帖子……你的判断是因为我对原文的措辞吗?
enum NativeEnum
{
  Enum1,
  Enum2
};

class WrapperClass
{
public:
  WrapperClass(ManagedNamespace::MyManagedClass^ inManaged):
    _Managed(inManaged)
  {}

  NativeEnum GetEnumValue()
  {
    return (NativeEnum)_Managed->EnumValue;
  }

private:
    gcroot<ManagedNamespace::MyManagedClass^> _Managed;
};
error C2440: 'type cast' : cannot convert from 'OtherNamespace::ManagedEnum' to 'OtherNamespace::NativeEnum'
1>          Conversion requires a constructor or user-defined-conversion operator, which can't be used by const_cast or reinterpret_cast
NativeEnum someMethod(ManagedEnum myEnum)
{
  return (NativeEnum)(int)myEnum;
}