有没有办法让C#编译器发出一个错误,如果一个开关(enum_val)缺少一个case语句? [英] Is there a way to get the C# compiler to emit an error if a switch(enum_val) is missing a case statement?

查看:177
本文介绍了有没有办法让C#编译器发出一个错误,如果一个开关(enum_val)缺少一个case语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才意识到我添加了一个价值在我枚举必须处理的价值观的名单,但我没赶上,直到运行时。我知道C#编译器真的很强大,当谈到反思和类型的反省,所以我在想,如果有一种方法来强制开关 / 情况语句以涵盖所有可能的枚举值?

I just realized I added a value to the list of "must-handle" values in my enum, but I didn't catch it until runtime. I know the C# compiler is really powerful when it comes to reflection and introspection of types, so I was wondering if there was a way to force a switch/case statement to cover all possible enum values?

例如:

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"

我想一个编译时的解决方案。

I want a compile-time solution.

推荐答案

刚刚抛出(双关语是无意的)这一点,你可以用一个字典( Func键&LT取代的switch-case; 为例):

Just by throwing (pun unintended) this out, you can replace the Switch-Case with a dictionary (Func<int,int> as an example):

Dictionary<Colors,Func<int,int>> d = new Dictionary<Colors, Func<int, int>>();
d.Add(Colors.Red, (x) => x+1);
d.Add(Colors.Blue, (x) => x+1);
d.Add(Colors.Green, (x) => x+1);
foreach (Colors color in Enum.GetValues(typeof(Colors)))
{
    if (!d.ContainsKey(color))
    {
        throw new Exception("Poor color " + color + " ignored");
    }
}

这篇关于有没有办法让C#编译器发出一个错误,如果一个开关(enum_val)缺少一个case语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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