Unreachable code detected in case statement

前端 未结 14 2365
终归单人心
终归单人心 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:09

    In this case, good practice imho would be to end each case with a return, like this:

    case Keys.Alt|Keys.D1:
        bool result;
        if (this._condition1) 
            { 
                result = true; 
            } 
            else 
            { 
                result = base.ProcessCmdKey(ref msg, keyData); 
            }
        return result;
    

    Or

    case Keys.Alt|Keys.D1:
        bool result = (this._condition1)
            ? true
            : base.ProcessCmdKey(ref msg, keyData); 
        return result;
    
    0 讨论(0)
  • 2020-12-06 17:11

    As the code is currently, the "break" commands will never be run nor will the final "return true" command. Removing these would get rid of the warnings.

    You might want to try for a solution with fewer return paths as it can make code harder to debug and understand. Something like this:

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool processed = false;
            switch (keyData)
            {
                case Keys.Alt | Keys.D1:
    
                    if (this._condition1)
                        processed = true;
    
                    break;
    
                case Keys.Control | Keys.U:
    
                    if (this._condition2)
                        processed = true;
    
                    break;
            }
    
            if (!processed)
                processed = base.ProcessCmdKey(ref msg, keyData);
    
            return processed;
        }
    
    0 讨论(0)
提交回复
热议问题