我刚刚意识到我在枚举中的"必须处理"值列表中添加了一个值,但直到运行时我才抓到它.我知道C#编译器在涉及类型的反射和内省时非常强大,所以我想知道是否有办法强制switch/ case语句覆盖所有可能的enum值?
例:
enum Colors
{
Red,
Blue,
Green,
Yellow
};
Colors c = ...;
switch (c)
{
case Colors.Red: // No error, Red is a Color
break;
case Colors.Blue:
case Colors.Green: // No error, Blue and Green handled as well
break;
} // whoops! "error: 'Colors.Yellow' unhandled"
// or even, "error: no 'default' and 'Colors.Yellow' unhandled"
Run Code Online (Sandbox Code Playgroud)
我想要一个编译时的解决方案.
Chr*_*rle 13
没有没有编译时间的方法来实现这一点.然而,非常简单的答案是有一个default处理程序,它只是抛出一个异常,"这个选项没有处理,boo".
switch (c)
{
case Colors.Red: // no error, Red is a Color
break;
case Colors.Blue:
case Colors.Green: // no error, Blue and Green handled as well
break;
default:
throw new Exception("Unhandled option: " + c.ToString());
}
Run Code Online (Sandbox Code Playgroud)