简体   繁体   English

从C ++ / CLI const向C#枚举赋值

[英]Assign value to C# enum from C++/CLI const

I've searched through the other answers similar to this topic, but haven't found anything completely relevant. 我搜索了与该主题相似的其他答案,但没有找到完全相关的内容。 I'm trying to assign values to some enumerations in C#, using values that are marked as static const in a C++/CLI file, which are compiled into a DLL and referenced in the C# project. 我正在尝试使用在C ++ / CLI文件中标记为静态const的值将值分配给C#中的某些枚举,这些值被编译成DLL并在C#项目中引用。 All of that works fine, except that it gives me the "The expression being assigned to 'XXX' must be constant", which I would expect, if the C++/CLI value wasn't a constant. 所有这些工作都很好,只是它给了我“分配给'XXX'的表达式必须是常量”,如果C ++ / CLI值不是常量,我希望可以这样做。 My C++/CLI code is auto-generated from 3rd-party vendor provided files, so my options for changing that side are extremely limited. 我的C ++ / CLI代码是由第三方供应商提供的文件自动生成的,因此更改该方面的选项非常有限。

Here's some excerpts: 以下是摘录:

The C++/CLI file: C ++ / CLI文件:

public ref class SEVERE_LEVEL sealed {
  public: 
    static const System::Int32 VALUE = 200;
  private:
    SEVERE_LEVEL() {}
};

And the C# file: 和C#文件:

public enum LoggerLevel {
  SevereLevel = SEVERE_LEVEL.VALUE  // This gives the "must be constant" error
}

There are several different log levels, each defined in their own separate class in the C++/CLI file. 有几种不同的日志级别,每种级别在C ++ / CLI文件中的单独类中定义。 I want to use the C# enum as a parameter type in some method calls to ensure only valid values are passed in. Any ideas how to make this work or suggestions on alternative designs? 我想在某些方法调用中使用C#枚举作为参数类型,以确保仅传递有效值。关于如何进行此项工作的任何想法或关于替代设计的建议?

The C++ const keyword doesn't map into anything in .NET. C ++ const关键字不会映射到.NET中的任何内容。

C++/CLI adds new context-sensitive keywords to match the .NET functionality: initonly and literal . C ++ / CLI添加了新的上下文相关关键字以匹配.NET功能: initonlyliteral

If you use literal System::Int32 VALUE = 200; 如果您使用literal System::Int32 VALUE = 200; then it should work. 那么它应该工作。 There's no magic to make the C# compiler define enums using values that aren't marked "literal" in the .NET metadata. 使C#编译器使用在.NET元数据中未标记为“文字”的值来定义枚举是没有魔术的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM