c# - 在 C# 中使用 "default"作为枚举

标签 c# enums default

我有一个关于使用“默认”作为枚举值的快速问题。我正在读取现有 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/

相关文章:

grails - 如何在 grails 中使用 Enum(不在域类中)

SQL Server : Find out default value of a column with a query

c++ - 使用 default 关键字指定的构造函数是否微不足道?

default - 如何在mantis中配置 "Assign To"列表

c# - 是否建议在高流量网站上使用 ASP.NET 用户管理系统

c# - 如果一个字符串存在于大量对象列表中,比较最快的(性能)方法是什么?

c# - 简单的 XNA 二维物理库

ruby - 在 ruby​​ 中交错两个枚举的最佳方法?

c# - Databinding ItemsControl (DataTemplate) 不更新/只在程序启动时接收值

fork 代码中的 Java NoSuchMethodError