是否可以在 C# 中定义一个带有关键字值的枚举?
我正在读取一些客户端数据,并且我已经为其中一个值定义了一个枚举,因此我可以使用 Enum.Parse(type, somestring)。
问题是他们只是添加了一个新值:“public”。是否可以定义一个同时也是保留字的枚举值?
IE:
public enum MyEnum {
SomeVal,
SomeOtherVal,
public,
YouGetTheIdea
}
如果没有,我想我会编写一个解析方法。
I have some client data that I am reading in, and I've defined an Enum for one of the values, so I can use Enum.Parse(type, somestring).
The problem is they just added a new value: "public". Is it possible to define an enum value that is also a reserved word?
I.E.:
public enum MyEnum {
SomeVal,
SomeOtherVal,
public,
YouGetTheIdea
}
If not I guess I'll be writing a parse method instead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以在变量名称前面添加
@
。这允许您使用关键字作为变量名称 - 所以@public
。请参阅此处。
来自 C# 规范:
You can prepend a
@
to the variable name. This allows you to use keywords as variable names - so@public
.See here.
From the C# spec:
是的,在名称前加上@。即
@public
yes, prefix the name with an @. i.e.
@public
如果您将
public
大写为Public
,它将不会被识别为关键字。关键字区分大小写。然而,作为一般实践,使用关键字名称(即使它们的大小写不同)是一个坏主意,因为如果意外地使用关键字代替标识符,可能会导致混乱,甚至会导致微妙的缺陷。
还可以在某些上下文(例如变量或成员声明)中使用
@
将保留字用作非关键字。然而,这不是一种常见的做法,只能是当您无法使用不同名称时的最后手段。因此,在您的情况下,您还可以使用
@public
将保留字用作枚举标识符。如果您选择使用
@
,请注意该符号仅在源代码中用于区分标识符和保留字。对于外界(以及在Enum.Parse()
等方法中)来说,枚举值的名称只是public
。If you capitalize
public
toPublic
it won't be recognized as a keyword. Keywords are case sensitive.As a general practice, however, it's a bad idea to use names that are keywords (even when they differ by case) as it can cause confusions, or even subtle defects if the keyword is accidentally used in place of the identifier.
It's also possible to use the
@
in certain contexts (like variable or member declarations) to use reserved words as non-keywords. However, it's not a common practice and should only be a means of last resort, when you can't use a different name.So in your case you could also use
@public
to use the reserved word as an enum identifier.If you chose to use
@
, be aware that the symbol is only used in your source code to differentiate the identifier from the reserved word. To the outside world (and in methods likeEnum.Parse()
), the name of the enum value is simplypublic
.不过,这样做并不是一个好主意。相反,向枚举添加更多信息:
PublicAccess 等
It's not really a great idea to do this though. Instead, add a bit more info to the enum:
PublicAccess etc
在 VB.Net 中,使用方括号 [...] 将关键字描述为标识符。
例子:
In VB.Net use square braces [...] to delineate a keyword as an identifier.
Example:
对于 VB.NET,请执行以下操作:
For VB.NET do the following: