I read this statement in a C# book.
Enumerations do not necessarily need to follow a sequential ordering, and need not have unique values.
If I understand that statement, it means one of this is acceptable (I don't know which):
1.
enum EmpType
{
Manager = 1,
Grunt = 1,
Contractor = 100,
VicePresident = 9
}
2.
enum EmpType
{
Manager = 10,
开发者_StackOverflowManager = 1,
Contractor = 100,
VicePresident = 9
}
Can someone please explain to me? I thought C# was supposed to be a subset of C/C++.
The first one would be valid, you may have duplicate Values
not duplicate Names
1 is correct, 2 is not.
As the book says, enums need not have unique values (example 2 shows enums with non-unique names). Names must be unique, as it is how the compiler matches it up to a value.
Actually - why not to check :) Each enum is subclass of System.Enum class (specially handled), each enum element is a static field initialized with a literal value - you cannot have two fields with the same names, but can have fields with the same values, so #1 will work, #2 won't.
Number 1 is acceptable. Number 2 throws a compile time exception. You can have multiple Equivalent values. But not equivalent duplicate names.
For example, suppose you want to define an enum for a companie's personnel job levels. You have staff, management. staff include sales department and IT department and it doesn't make any difference for you if a person is in sales or IT, He/she is considered staff anyway. You can define the following enum:
public enum PersonnelLevels
{
Management=0,
Sales=1,
IT=1
}
Refering to enum (C# Reference):
The default underlying type of enumeration elements is int.
You can assign any integer value to any enumuration element. You can assign duplicated values to different elements. However, elements names must be unique.
That means, block one is correct. But, block two is not.
精彩评论