我有一个关于使用“默认”作为枚举值的快速问题。我正在读取现有 XML 文件的内容并将元素值解析为枚举。以下是 XML 文件中内容的示例:
<userpref_load_policy>default</userpref_load_policy>
不幸的是,我无法执行以下操作,因为“默认”是关键字! 'at_start' 和 'in_background' 是此元素的其他允许值。
public enum LoadPolicy { default, at_start, in_background }
有没有一种“简单”的方法可以将默认值用作枚举值或欺骗编译器?我有一种讨厌的感觉,我需要求助于自定义扩展方法。我这样说是因为我在写回 XML 文件时调用 .ToString() 方法(并且有很多枚举..)
提前感谢任何指点,伊恩
最佳答案
是的,您可以使用 @
将其用作标识符:
public enum LoadPolicy { @default, at_start, in_background }
来自 C# 5 规范,第 2.4.2 节:
The rules for identifiers given in this section correspond exactly to those recommended by the Unicode Standard Annex 31, except that underscore is allowed as an initial character (as is traditional in the C programming language), Unicode escape sequences are permitted in identifiers, and the "@" character is allowed as a prefix to enable keywords to be used as identifiers.
我个人更喜欢在枚举本身中使用更惯用的名称,但在枚举值和它们的 XML 表示之间有一个映射。但如果您真的必须使用枚举值名称,这将起作用...
关于c# - 在 C# 中使用 "default"作为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19452917/