Is there a way to get the C# compiler to emit an error if a switch(enum_val) is missing a case statement?

前端 未结 8 1899
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 04:27

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 com

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 05:04

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

    Dictionary> d = new Dictionary>();
    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");
        }
    }
    

提交回复
热议问题