An enum
is a convenient way to use names instead of numbers, in order to denote something. It makes your code far more readable and maintainable than using numbers. For instance, let that we say that 1 is red and 2 is green. What is more readable the following:
if(color == 1)
{
Console.WriteLine("Red");
}
if(color == 2)
{
Console.WriteLine("Green");
}
or this:
enum Color { Red, Green}
if(color == Color.Red)
{
Console.WriteLine("Red");
}
if(color == Color.Green)
{
Console.WriteLine("Green");
}
Furthermore, let that you make the above checks in twenty places in your code base and that you have to change the value of Red from 1 to 3 and of Green from 2 to 5 for some reason. If you had followed the first approach, then you would have to change 1 to 3 and 2 to 5 in twenty places ! While if you had followed the second approach the following would have been sufficient:
enum Color { Red = 3 , Green = 5 }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…