基本上,我需要将几个常量从非托管 C++ 公开到我的 C# 库。以下方法有效,但我认为它有异味:
在我的非托管 C++ 代码中:
class Mappings
{
public:
static const int North = 0 ;
static const int West = 1 ;
static const int East = 2 ;
static const int South = 3 ;
在我的托管 C++ 层中:
public:
static const int North = Mappings::North ;
static const int West = Mappings::West ;
static const int East = Mappings::East ;
static const int South = Mappings::South ;
有没有更简洁/更短的方法,这样我就不必将代码重复两次?
最佳答案
使用public enum class
关键字声明托管枚举类型。是的,这很丑陋,因为您无法导出 native C++ 枚举。不幸的是,你需要重复一遍。
C++11 也采用了 enum class
关键字,但它仍然与托管版本不同。这导致了 C++/CLI 中的语法歧义,因为这两种语言风格现在使用相同的关键字。编译器可以从可访问性关键字(使用public
或private
)看出区别,它对原生C++无效。
关于c++ - 如何将非托管 C++ 中的常量公开给 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8038775/