Enums, overlapping values, C#
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
T开发者_如何学Gohanks
Let's take a simple example
enum PrivilegeLevel
{
None,
Reporter,
Reviewer,
Admin,
DefaultForNewUser = None,
DefaultForProjectOwner = Reviewer,
};
The idea behind enumerated types is to create new data types that can take on only a >restricted range of values.
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.
精彩评论