枚举、重叠值、C#
提前道歉,因为我确信以前一定有人问过这个问题,但我找不到。
只是有一个惊喜,一位同事和我都在枚举中添加了相同的值,并且编译了它,例如
enum MyEnum
{
mine = 1,
his = 1
}
看起来 C/C++ 也支持这个(?)。这种行为有什么原因吗?在什么情况下它有用?我看到一个具有不同人类语言的案例(one = 1,eins = 1 等),但我不相信
谢谢
Apologies in advance as I'm sure someone must have asked this before but I can't find it.
Just had a surprise, a colleague and I both added the same value in for an enum, and it compiled, e.g.
enum MyEnum
{
mine = 1,
his = 1
}
Looks like C/C++ supports this also (?). Any reason for this behaviour, any cases where it's useful? I saw one case with difference human languages (one = 1, eins = 1, etc) but I'm not convinced
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们举一个简单的例子
Let's take a simple example
您所做的事情是合法的,编译器不应该给出任何错误,因为 enum 只代表一个常量。您只是给常量一个合乎逻辑的名称。
当需要分隔命名常量时,可以为两个或多个枚举常量分配相同的值。假设您有一个配色方案,两者背后都使用相同的基本颜色,但这些方案需要在逻辑上分开。然后您可以对枚举常量使用相同的值。但仍然有更好的方法可以做到这一点。
What you did is legal and compiler is not ought to give any errors as enum represents just a constant. You are just giving your constant a logical name.
You can assign same values to to two or more enum constants when you need to separate the named constants. Say you have a color scheme both of which used the same basic color behind them, but the schemes need to be logically separated. Then you can use same values for enum constants. But still there are better ways to do that.