简体   繁体   English

在C#中使用“default”作为枚举

[英]Use of “default” as an enum in C#

I have a quick question regarding the use of "default" as an enum value. 我有一个关于使用“默认”作为枚举值的快速问题。 I'm reading the contents of an existing XML file and parsing the element values to enums. 我正在读取现有XML文件的内容并将元素值解析为枚举。 Here is and example of what is in the XML file: 以下是XML文件中的示例:

<userpref_load_policy>default</userpref_load_policy>

Unfortunately I cannot do the following as 'default' is a keyword! 不幸的是我无法执行以下操作,因为'default'是一个关键字! 'at_start' and 'in_background' are the other permitted values for this element. 'at_start'和'in_background'是此元素的其他允许值。

public enum LoadPolicy { default, at_start, in_background }

Is there an "easy" way to use default as an enum value or trick the compliler? 是否有“简单”的方法将默认值用作枚举值或欺骗编译器? I have a nasty feeling I will need to resort to a custom extension method. 我有一种讨厌的感觉,我需要求助于自定义扩展方法。 I say this as I'm calling the .ToString() method when writing the XML file back out (and there are lots of enums..) 我说这是因为我在写回XML文件时调用.ToString()方法(并且有很多枚举...)

Thanks in advance for any pointers, Iain 伊恩,提前感谢任何指针

Yes, you can use it as an identifier using @ : 是的,您可以使用@作为标识符:

public enum LoadPolicy { @default, at_start, in_background }

From the C# 5 spec, section 2.4.2: 从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. 本节中给出的标识符规则完全符合Unicode标准附件31建议的规则,但允许下划线作为初始字符(在C编程语言中是传统的),标识符中允许使用Unicode转义序列,并且允许使用“@”字符作为前缀,以使关键字可用作标识符。

I would personally prefer to use more idiomatic names within the enum itself, but have a mapping between the enum values and their XML representations. 我个人更喜欢在枚举本身中使用更多的惯用名,但是在枚举值和它们的XML表示之间有一个映射。 But this will work if you really have to use the enum value names... 但是,如果您真的必须使用枚举值名称,这将有效...

Any keyword can be escaped using an @ : 任何关键字都可以使用@转义:

public enum LoadPolicy { @default, at_start, in_background }

The @ is just a marker; @只是一个标记; not really part of the name. 不是名字的一部分。 So later when you use it can just write: 所以稍后当你使用它时可以写:

LoadPolicy x = LoadPolicy.default;

The @ is only needed when the meaning is ambiguous. 仅在含义不明确时才需要@

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

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