如何定义多个值映射到单个标签的枚举?

时间:2013-03-11 14:59:36

标签: c# .net enums bitflags

假设为了这个例子,我试图解析一个文件,该文件指定记录中的两个任意字节代表星期几,因此:

DayOfWeek:

 - 0    = Monday
 - 1    = Tuesday
 - 2    = Wednesday
 - 3    = Thursday
 - 4    = Friday
 - 5    = Saturday
 - 6    = Sunday
 - 7-15 = Reserved for Future Use

我可以定义一个枚举来映射到这个字段,因此:

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
     ReservedForFutureUse
}

但是如何为ReservedForFutureUse定义有效值?理想情况下,我想做类似的事情:

public enum DaysOfWeek
    {
         Monday = 0,
         Tuesday = 1,
         Wednesday = 2,
         Thursday = 3,
         Friday = 4,
         Saturday = 5,
         Sunday = 6
         ReservedForFutureUse = {7,8,9,10,11,12,13,14,15}
    }

这个问题只会因为更复杂的领域而加剧;例如,假设在这种情况下,7和8都映射到相同的错误情况或其他内容。如何在C#枚举中捕获此要求?

2 个答案:

答案 0 :(得分:4)

带枚举的一个有趣的怪癖是,定义为某个枚举类型的变量可以包含未由该枚举的任何成员定义的值:

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
}

// in other code
DaysOfWeek someDay = (DaysOfWeek)42; // this is perfectly legal

这意味着您并不需要定义可能出现的所有可能值,而只需指定那些对您的代码有意义的值。然后你可以使用一些" catch-all" if - 或switch - 阻止处理未定义的值:

switch (someDay)
{
    case DaysOfWeek.Monday:
    {
        // do monday stuff
        break;
    }
    case DaysOfWeek.Tuesday:
    {
        // do tuesday stuff
        break;
    }
    // [...] handle the other weekdays [...]
    default:
    {
        // handle undefined values here
        break;
    }
}

答案 1 :(得分:3)

虽然给定的基础值可以映射到多个enum值,但enum值可以只有一个基础值。

你可以这样做

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
     Reserved1 = 7
     ...
     Reserved8 = 15
}