本文介绍了运营商枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是出于好奇,问这
像下面
的表达有一个
A =(条件)? X:Y; //两个输出
为什么我们就不能对枚举操作?结果
说,
myvalue的= F ??? fnApple():fnMango():fnOrange(); //没有。在枚举定义
指定输出
而不是switch语句(尽管重构是可能的)
枚举水果
{
苹果,
芒果,
橙色
};
水果F = Fruit.apple;
或者是一些无用的运营商
解决方案
我不能说我曾经想这样的运营商 - 这将是令人难以置信的脆弱依靠的顺序枚举值。您可以轻松地使用交换机:
开关(F)
{
情况下Fruit.Apple:myvalue的= fnApple();打破;
情况下Fruit.Mango:myvalue的= fnMango();打破;
情况下Fruit.Orange:myvalue的= fnOrange();打破;
默认:抛出新ArgumentOutOfRangeException(F);
}
另外,创建一个映射:
静态只读字典<水果,Func键<富>> FruitFunctions =
新字典<水果,Func键<富>> {
{Fruit.Apple,fnApple}
{Fruit.Mango,fnMango}
{Fruit.Orange,fnOrange}
};
...
myvalue的= FruitFunctions [F]();
我已经用在各种情况下这两种技术,并远远甩宁愿建议的运营商,我只怕。
Just out of curiosity, asking this
Like the expression one below
a = (condition) ? x : y; // two outputs
why can't we have an operator for enums?
say,
myValue = f ??? fnApple() : fnMango() : fnOrange(); // no. of outputs specified in the enum definition
instead of switch statements (even though refactoring is possible)
enum Fruit
{
apple,
mango,
orange
};
Fruit f = Fruit.apple;
Or is it some kind of useless operator?
解决方案
I can't say I've ever wanted such an operator - which would be incredibly brittle by relying on the ordering of the enum values. You can easily use a switch:
switch (f)
{
case Fruit.Apple: myValue = fnApple(); break;
case Fruit.Mango: myValue = fnMango(); break;
case Fruit.Orange: myValue = fnOrange(); break;
default: throw new ArgumentOutOfRangeException("f");
}
Alternatively, create a map:
static readonly Dictionary<Fruit, Func<Foo>> FruitFunctions =
new Dictionary<Fruit, Func<Foo>> {
{ Fruit.Apple, fnApple },
{ Fruit.Mango, fnMango },
{ Fruit.Orange, fnOrange }
};
...
myValue = FruitFunctions[f]();
I've used both techniques in various situations, and far prefer them to the suggested operator, I'm afraid.
这篇关于运营商枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!