我能避免投枚举值当我尝试使用或退货吗? [英] Can I avoid casting an enum value when I try to use or return it?

查看:137
本文介绍了我能避免投枚举值当我尝试使用或退货吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下枚举:

public enum ReturnValue{
    Success = 0,
    FailReason1 = 1,
    FailReason2 = 2
    //Etc...
}

我能避免铸造,当我回来,是这样的:

Can I avoid casting when I return, like this:

public static int main(string[] args){
    return (int)ReturnValue.Success;
}

如果不是,为什么不是一个枚举值当作一个int默认?

If not, why isn't an enum value treated as an int by default?

推荐答案

枚举应该是类型安全的。我认为他们并没有使他们含蓄地浇注料,以阻止其他用途。虽然框架允许您在一个恒定值分配给他们,你应该重新考虑你的意图。如果你主要使用枚举存储常量值,可以考虑使用一个静态类:

enums are supposed to be type safe. I think they didn't make them implicitly castable to discourage other uses. Although the framework allows you to assign a constant value to them, you should reconsider your intent. If you primarily use the enum for storing constant values, consider using a static class:

public static class ReturnValue
{
    public const int Success = 0;
    public const int FailReason1 = 1;
    public const int FailReason2 = 2;
    //Etc...
}

这可以让你做到这一点。

That lets you do this.

public static int main(string[] args){
    return ReturnValue.Success;
}

修改

在你的执行的要提供值枚举是当你想将它们组合。参见下面的例子:

When you do want to provide values to an enum is when you want to combine them. See the below example:

[Flags] // indicates bitwise operations occur on this enum
public enum DaysOfWeek : byte // byte type to limit size
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64,
    Weekend = Sunday | Saturday,
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

这枚举然后可以通过按位数学消耗。看到对于一些应用下面的例子

This enum can then be consumed by using bitwise math. See the below example for some applications.

public static class DaysOfWeekEvaluator
{
    public static bool IsWeekends(DaysOfWeek days)
    {
        return (days & DaysOfWeek.Weekend) == DaysOfWeek.Weekend;
    }

    public static bool IsAllWeekdays(DaysOfWeek days)
    {
        return (days & DaysOfWeek.Weekdays) == DaysOfWeek.Weekdays;
    }

    public static bool HasWeekdays(DaysOfWeek days)
    {
        return ((int) (days & DaysOfWeek.Weekdays)) > 0;
    }

    public static bool HasWeekendDays(DaysOfWeek days)
    {
        return ((int) (days & DaysOfWeek.Weekend)) > 0;
    }
}

这篇关于我能避免投枚举值当我尝试使用或退货吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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