如何使用具有多个枚举值的开关?

时间:2014-05-08 05:34:15

标签: haxe

我正在尝试这段代码:

enum SideType
{
    Vex;
    Cav;
    Plano;
}

function drawLense(aLeftType:SideType){

switch (aLeftType) 
        {
            case Cav:
                leftCenter = -aRadius - d * 0.5;

            case Vex:
                leftCenter = -Math.cos(( -90 + offset) * Math.PI / 180) * aRadius-d*0.5;

            case Plano:return ;
            case Cav, Vex:
                points1= drawCurve(1, -90 + offset + trim, 180 - offset * 2 - (trim * 2), leftCenter, aRadius);
                _LB = points1[0];
                _LA = points1[1];

        }
}

但是我在编译时遇到错误:

characters 8-16 : This pattern is unused

所以,它指的是Cav,Vex:

在上述情况下如何检查Cav或Vex?

修改

我发现如果我移除了箱子Cav& Case Vex,然后案例Cav,Vex将会工作,但这不是我想要的,我能否在一个或者经验中重复使用模式? 喜欢(案例Cav || Vex)?

案例(Cav || Vex)将导致:

src/com/optics/components/Lense.hx:343: characters 8-38 : Case expression must be a constant value or a pattern, not an arbitrary expression

4 个答案:

答案 0 :(得分:4)

aLeftType的值只有3个选项,VexCavPlano

var aLeftType = Vex;
switch (aLeftType) 
{
    case Cav:
        // If aLeftType is `Cav`, run this line.
    case Vex:
        // If aLeftType is `Vex`, run this line.
    case Plano:
        // If aLeftType is `Plano`, run this line.
    case Cav, Vex:
        // If aLeftType is `Vex` or `Plano`, run this line...
        // But the first 2 cases already covered `Vex` and `Plano`,
        // so it will never be reached.
}

所以,第四种情况的代码永远不会运行。它类似于:

if (a == 1) {
    trace("a is 1");
} else if (a == 1) {
    trace("a is really 1"); // This can never be reached.
}

这意味着,你必须再想一想你真的想做。

答案 1 :(得分:3)

通常当你想在不同的情况下做同样的事情时,你可以为它做一个函数:)

function drawLense(aLeftType:SideType){

        switch (aLeftType) 
        {
            case Cav:
                leftCenter = -aRadius - d * 0.5;
                functionCalledIfCavOrVex();

            case Vex:
                leftCenter = -Math.cos(( -90 + offset) * Math.PI / 180) * aRadius-d*0.5;
                functionCalledIfCavOrVex();

            case Plano:return ;
        }
}

function functionCalledIfCavOrVex(/*...*/){
        points1= drawCurve(1, -90 + offset + trim, 180 - offset * 2 - (trim * 2), leftCenter, aRadius);
        _LB = points1[0];
        _LA = points1[1];
}

答案 2 :(得分:1)

简短回答:目前还没办法,你只能在一个地方匹配一个枚举选项(不计算看守选项)。因此,为每个枚举选项复制代码并过上幸福的生活(此代码也更容易阅读)或使用秒开关(在某些更复杂的情况下可能更短更容易)。

答案 3 :(得分:-1)

尝试:

case Cav | Vex:
  trace("cav or vex");

希望它有所帮助。