且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C#,C ++ / CLI和C ++共享一个枚举

更新时间:2023-02-12 12:21:34

只要把你的 #includeEnum.cs指令在外部命名空间中解决命名冲突。



编辑:Brent建议的变体是使用 #define 替换在.cs文件中声明的其中一个命名空间(甚至枚举名称本身)。这也避免了命名冲突,而不会使命名空间层次更深。


I have a library that consists of three parts. First is native C++, which provides the actual functionality. Second is a C++/CLI wrapper/adaptor for the C++ library, to simplify the C# to C++ transition. Finally I have a C# library, which invokes the C++ library through the C++/CLI adaptor.

Right now there I have two sets of parallel enum definitions, one stored in a .cs file and the other in a .h file. This poses a double problem:

  1. I have dual maintenance. I must always synchronize changes of an enum in both file locations.
  2. The namespace used by both enums should be identical but the C++/CLI wrapper, which views both sets of enums and translates between them, incurs a naming collision.

Right now I'm not sure a solution such as this or that would solve both problems. Thoughts?

Just put your #include "Enum.cs" directive inside an outer namespace to resolve the naming collision.

EDIT: A variation suggested by Brent is to use #define to substitute one of the namespaces (or even the enum name itself) declared in the .cs file. This also avoids the naming collision, without making the namespace hierarchy deeper.