在方法参数中约束枚举值

fea*_*net 2 .net c# parameters enums constraints

enum Fruit
{
    Banana,
    Orange,
    Strawberry
    ...
    ...
    // etc, very long enum
}


PeelFruit(Fruit.Orange);
PeelFruit(Fruit.Banana);
PeelFruit(Fruit.Strawberry); // huh? can't peel strawberries!
Run Code Online (Sandbox Code Playgroud)

抱歉这个蹩脚的例子,但希望你能得到这个想法.有没有办法约束PeelFruit将接受的枚举值?

显然我可以通过开关或其他东西在方法中检查它们,但是如果有一种方法可以做到这一点很酷a)更紧凑,并且b)会导致编译时错误,而不是运行时错误.

[Fruit = Orange,Bannana]
void PeelFruit(Fruit fruit) { ... }
Run Code Online (Sandbox Code Playgroud)

Jef*_*nal 7

对于基本语言功能,这是不可能的(虽然编译时检查只适用于高级版本,但可以使用代码合同).实际上,您甚至无法将输入限制在您定义的值中!只要调用者将其转换为第一个参数,接受参数的方法将接受任何(或任何枚举的类型,如果它不是整数):enumFruitintFruit

PeelFruit((Fruit)10000); // Not a Fruit? Not a problem!
Run Code Online (Sandbox Code Playgroud)