9

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

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# 枚举中捕获这一要求?

4

2 回答 2

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-block 来处理未定义的值:

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;
    }
}
于 2013-03-11T15:27:32.707 回答
3

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

你可以这样做

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
     Reserved1 = 7
     ...
     Reserved8 = 15
}
于 2013-03-11T15:02:01.483 回答