什么是Enum有用? [英] What is Enum useful for?
问题描述
在读取一些有关枚举的问题和答案之后,我没有发现它真的很有用...这是类和变量之间的东西,但我知道我可以在哪里使用它,所以这将是一个更有用的类,或一些变量例如。
还有其他的事情你可以做的和使用它们的原因,但是我使用枚举的主要原因是防止无效参数的可能性。例如,想象下面的方法:
public void doSomethingWithAMonth(int monthNum);
这不仅不明确(月份索引是从1开始还是在0?),但是可以给出正确的无效数据(13+,负数)。如果您有JAN,FEB等的枚举 Month
,则签名将变为:
public void doSomethignWithAMonth(Month month);
调用此方法的代码将更加易读,无法提供无效数据。 >
After reading some questions and answers about enum I don't find it really useful...
It's something between class and a variable but I know where can I use it so it would be more useful then a class, or a couple of variables for example.
There are other things you can do and reasons to use them, but the primary reason I use enums is to prevent the possibility of an invalid parameter. For example, imagine the following method:
public void doSomethingWithAMonth(int monthNum);
This is not only ambiguous (do month indexes start at 1, or at 0?), but you can give down-right invalid data (13+, negative numbers). If you have an enum Month
with JAN, FEB, etc. the signature becomes:
public void doSomethignWithAMonth(Month month);
Code calling this method will be far more readable, and can't provide invalid data.
这篇关于什么是Enum有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!