问题描述
每次我使用 List< T>
, string
, bool
等进行编码时,我都看不到任何使用我认为 enum
是一个常量,但实际上,我们在哪里实际使用它.如果可以的话,我们只能使用
While I code every time I used List<T>
, string
, bool
etc. I did't see anywhere a use of an enum.
I have an idea that enum
is a constant but in practice, where do we actually use it. If at all we can just use a
public const int x=10;
我们实际在哪里使用它?
Where do we actually use it?
请帮助我
推荐答案
枚举
是使用名称而不是数字来表示某些内容的便捷方法.它使您的代码比使用数字更具可读性和可维护性.例如,让我们说1是红色,2是绿色.以下内容更具可读性:
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");
}
或者这个:
enum Color { Red, Green}
if(color == Color.Red)
{
Console.WriteLine("Red");
}
if(color == Color.Green)
{
Console.WriteLine("Green");
}
此外,让您在代码库中的二十个位置进行上述检查,并且由于某种原因必须将Red的值从1更改为3,将Green的值从2更改为5.如果您采用了第一种方法,则必须在20个地方将1更改为3,将2更改为5!如果您采用了第二种方法,那么下面的内容就足够了:
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 }
这篇关于什么是枚举,在哪里可以使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!