如何定义一个枚举,其中多个值映射到单个标签
本文关键字:标签 映射 单个 枚举 何定义 定义 一个 | 更新日期: 2023-09-27 18:03:16
在本例中,假设我试图解析一个文件,该文件指定记录中的两个任意字节表示星期几,因此:
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#枚举中捕获这个需求?
枚举的一个奇怪之处在于,定义为某种枚举类型的变量可以保存未被该枚举的任何成员定义的值:
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;
}
}
尽管给定的底层值可以映射到多个enum
值,但enum
值只能有一个底层值。
你可以这样做
public enum DaysOfWeek
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6
Reserved1 = 7
...
Reserved8 = 15
}