使用枚举作为int是一个好习惯吗? [英] Is it a good practice to use enum as int?

查看:117
本文介绍了使用枚举作为int是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在一个类中有一个变量state。我想把它声明为整数,所以我可以保存一些if语句。

  int state; 

一种方法是声明枚举状态{One = 0,Two = 1,Three = 3},然后在switch语句中,它将成为:

  switch(state)
{
案例一:
dosomething();
break;
案例二:
dosomething();
break;
case三:
dosomething();
break;
}

那么,这样使用枚举是一个好习惯吗?
有更好的方法吗?



谢谢!

解决方案

是的,这是一个很好的方法。您通常使用枚举使生活更轻松,许多不同的数字并不真的告诉其他编码人员什么都不是很有用。



所以这是一个非常好的使用方法,它使您的代码可读和可理解。



Altough as @James McNellis指出,命名你的枚举像1,2,3,4是一个坏主意,因为它不能表达真正的作用。



但我怀疑这只是一个



请考虑这一点:

  switch operationState)
{
case等待:
dosomething();
break;
case运行:
dosomething();
break;
case已结束:
dosomething();
break;
}

在这种情况下,操作是:等待,运行或结束,这使它可读和可理解。现在考虑没有枚举的方式:

  switch(iState)
{
case 997:
dosomething();
break;
case 998:
dosomething();
break;
案例999:
dosomething();
break;
}

997告诉你什么?绝对没有!使用可读和可理解的代码,使每个人的生活更轻松。


So, I have a variable "state" in a class. I want to declare it as an integer so I can save some if statements.

int state;

One way to do this is to declare an enum State {One = 0, Two = 1, Three = 3}, and then in the switch statement, it would become:

switch (state)
{
case One:
    dosomething();
    break;
case Two:
    dosomething();
    break;
case Three:
    dosomething();
    break;
}

So, is it a good practice to use enum like this? Is there a better way to do this?

Thanks!

解决方案

Yes that is a good way to do it. You generally use enums to make life easier, a lot of different numbers that don't really tell other coders anything isn't quite helpful.

So this is a perfectly good way of using it, it makes your code readable and understandable.

Altough as @James McNellis pointed out, naming your enums like "1,2,3,4" is a bad idea, since it doesn't express what it really does.

But I suspect that was only an example from your side.

Consider this instead:

switch (operationState)
{
    case Waiting:
        dosomething();
        break;
    case Running:
        dosomething();
        break;
    case Ended:
        dosomething();
        break;
}

In this case, the "operation" is either: Waiting, Running or Ended, which makes it readable and understandable. Now consider the way without enums:

switch (iState)
{
    case 997:
        dosomething();
        break;
    case 998:
        dosomething();
        break;
    case 999:
        dosomething();
        break;
}

What does 997 tell you? Absolutely Nothing! Use readable and understandable code to make everyones life easier.

这篇关于使用枚举作为int是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆