2014-11-14 111 views
0

我有一个C#类:无法施展C#枚举C++枚举当枚举是第三装配

public class MyManagedClass 
{ 
    public ManagedEnum EnumValue {get; set;} 
} 

它使用C#枚举

public enum ManagedEnum 
{ 
    Enum1, 
    Enum2 
} 

这是由一个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; 
}; 

现在,只要在C#类和C#枚举在同一个组件,这工作正常。

但如果C#枚举在不同的C#组件中,C#类仍然建立罚款,但试图编译C++类产生的错误:

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 

回答

1

在试用Aaron P的答案时,我发现问题在于我的C++项目没有将枚举作为参考的C#程序集。一旦我添加了引用,它一切正常。

+0

您应该将其标记为答案。 – t3chb0t

1

尝试获得潜在价值,然后转换为本地枚举。

这是一种粗糙的做法,但在您的情况下可能就足够了。

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

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

+0

这不提供问题的答案。要批评或要求作者澄清,在他们的帖子下留下评论 - 你总是可以评论你自己的帖子,一旦你有足够的[声誉](http://stackoverflow.com/help/whats-reputation),你会能够[评论任何帖子](http://stackoverflow.com/help/privileges/comment)。 –

+0

对不起,我是新来张贴在这里,正在编辑帖子,因为你在评论它... –

+0

是你的判断,因为我如何措辞原来的句子? –