C# 枚举条目名称中可以有连字符吗
有没有办法让枚举条目的名称中带有连字符“-”,例如:
enum myEnum
{
ok,
not-ok,
}
我看到了关于 具有友好名称的枚举 但是,如果我可以直接使用连字符,它会节省我的一些工作。
更新:我想使用连字符的原因是它可以轻松地使用枚举来表示我无法控制的设置值列表,例如:
rejected
replaced
local-bye
remote-bye
Is thre any way to have an enum entry with a hyphen, "-", in the name, for example:
enum myEnum
{
ok,
not-ok,
}
I've seen the question about enums having friendly names however it would save me a bit of work if I can use a hyphen directly.
Update: The reason I want to use a hyphen is it makes it easy to use an enum for lists of set values which I have no control over such as:
rejected
replaced
local-bye
remote-bye
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不可以,不允许使用连字符。
标识符
您显然可以将连字符替换为下划线,但正如 @benPearce 所建议的,CamelCase 将是更好的选择,并且符合大多数 C# 编码标准。
No, a hyphen is not allowed.
Identifiers
You could obviously replace the hyphen with an underscore, but as @benPearce suggested, CamelCase would be a better choice, and in line with most C# coding standards.
假设您有:
c 设置为 200 还是 0 ?
允许标识符中使用连字符将使语言几乎无法进行词法分析。这种语言已经足够难以分析
<<
和>>
的含义,每个都有两个完全不同的含义;我们不想让自己变得更加困难。命名指南规定对枚举值使用 CamelCasing;遵循指导方针。
Suppose you have:
Is c set to 200, or 0 ?
Allowing hyphens in identifiers would make the language almost impossible to analyze lexically. This language is already hard enough to analyze what with
<<
and>>
each having two completely different meanings; we don't want to make it harder on ourselves.The naming guidelines say to use CamelCasing for enum values; follow the guidelines.
如果有人需要使用连字符,我认为这种方法可以提供帮助:在枚举声明中使用下划线,然后用连字符替换下划线。
这不是最佳实践,但如果您无法控制“someValue”并且需要使用枚举,则可以提供帮助。
In case somebody needs to use hyphens I think this approach can help: Use underscore in your enum declaration and then replace the underscore with hyphen.
Not the best practice, but can help if you don't have control over "someValue" and need to use enums.
你说“我很乐意遵循这些指南,但是需要枚举来表示的字符串列表超出了我的控制范围”。由于这就是您需要连字符的原因,因此我建议您重写所需枚举的 toString() 方法,并在需要表示名称的代码中调用 toString() 方法。
You say "I'd happily follow the guidelines but the string list the enum is needed to represent is out of my control". Since this is why you want hyphens, I suggest you override the toString() method of the enums you need this for, and call toString() in your code where you need to represent the names.