Unreachable code detected in case statement

前端 未结 14 2364
终归单人心
终归单人心 2020-12-06 16:37

I have a code:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Alt|Ke         


        
相关标签:
14条回答
  • 2020-12-06 17:03

    A switch statement is not necessary here at all, avoiding the problem altogether:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
    { 
        return
            (keyData == Keys.Alt|Keys.D1 && this._condition1) ||
            (keyData == Keys.Control|Keys.U && this._condition2) ||
            base.ProcessCmdKey(ref msg, keyData); 
    }
    
    0 讨论(0)
  • 2020-12-06 17:04

    break is not necessary if all paths in a case statement end with a return. Do not use it then, otherwise you will get the mentioned warning.

    0 讨论(0)
  • 2020-12-06 17:04

    Break statement will never be executed, cause you return from the method. So I suggest to remove the unnecessary break.

    0 讨论(0)
  • 2020-12-06 17:07

    There's nothing wrong with removing the break statement here.

    0 讨论(0)
  • 2020-12-06 17:07

    According to your code, all the break(s) and the last statement are never reached, for there are the return statements before.

    You could rewrite your code like this:

        switch (keyData)
        {
            case Keys.Alt|Keys.D1:
                if (this._condition1) return true;
                else goto default;
    
            case Keys.Control |Keys.U:
                if (this._condition2) return true;
                else goto default;
    
            default:
                return base.ProcessCmdKey(ref msg, keyData);
        }
    
    0 讨论(0)
  • 2020-12-06 17:08

    I understand that this doesn't answer the question directly, but inspired by the various answers here I just wanted to add another variation on how the "switch" could be structured:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Alt|Keys.D1 && _condition1)
            return true;
    
        if (keyData == Keys.Control|Keys.U && _condition2)
            return true;
    
        // ...repeat for other variations
    
        return base.ProcessCmdKey(ref msg, keyData);
    }
    
    0 讨论(0)
提交回复
热议问题