何时使用Enum或Class [英] When to use Enum or Class

查看:78
本文介绍了何时使用Enum或Class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有3个应用程序状态,并且它具有固定的值.枚举或类常量的最佳方法是什么?

Here I have 3 application status, and it has a fixed values. What is the best way to do this, enum or class constants?

public enum Status
        {
            ENTERED = 1,
            APPROVED = 2,
            CANCELLED = 3
        };





public class Status
{
    public const int ENTERED  = 1;
    public const int APPROVED = 2;
    public const int CANCELLED = 3;
}

When to use enum and constant variable?

推荐答案

枚举.
如果您不担心特定的值,则可以使用枚举来确保它们不相同-为此使用类取决于您正确地做到这一点.

Enum.
If you are not worried about the particular values, then using an enum allows you to let it ensure that they are not the same - using a class for this relies on you getting it right.

public enum Status
        {
            ENTERED,
            APPROVED,
            CANCELLED
        };


另外,枚举是值类型,而不是引用类型,并且比类(具有构造函数等)在整个系统上的开销更少.

当您需要特定的数据类型时,请使用常量值:浮点数,字符串,字符-枚举只能是枚举(但可以通过在枚举定义中指定char来使用除char以外的任何整数基类型)


In addition an enum is a value type, rather than a reference type, and put less overhead on the whole system than a class (which has a constructor, etc.)

Use constant values when you need specific data types: floats, strings, characters - and enum can only be an enum (but you can use any of the integral base types except char by specifying it in the enum definition)


这篇关于何时使用Enum或Class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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