【问题标题】:switch between two cases using GOTO使用 GOTO 在两种情况之间切换
【发布时间】:2019-03-11 15:59:12
【问题描述】:

我想使用 goto 在 2 个案例之间切换(当案例 1 运行时,转到案例 2,然后当案例 2 运行时,再次转到案例 1,依此类推)但是在案例 2 之后,案例 1 不起作用. 这是我的代码:

case 1:
    //Create a new picker
    FileOpenPicker filePicker = new FileOpenPicker();

    //Add filetype filters.  In this case wmv and mp4.
    filePicker.FileTypeFilter.Add(".wmv");
    filePicker.FileTypeFilter.Add(".mp4");

    filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

    StorageFile file = await filePicker.PickSingleFileAsync();

    if (file != null)
    {
        mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
        mediaPlayerElement.MediaPlayer.Play();
    }

    openButton.Content = "Close";
    break;
case 2:
    mediaPlayerElement.Source = null;
    openButton.Content = "Open";
    goto case 1;

【问题讨论】:

  • 将你的逻辑移动到调用函数的函数中,不要使用 goto,否则你的代码将无法理解
  • 定义“不起作用”。它抛出异常(哪一个)?它的行为不像预期的那样(你期望什么,你得到了什么)?另外,为什么不使用while 而不是goto
  • case 1 以break; 结尾,所以不会转到 case 2
  • @RobinBennett 当我转到案例 2 时,它打开了文件浏览器,每次我关闭文件浏览器时,它都会再次打开,所以我不得不按 alt-f4 3 次才能关闭程序.
  • 这不是你想要的吗?这就是您的问题所要求的。

标签: c# uwp switch-statement goto


【解决方案1】:

您应始终避免使用gotos,否则您的代码将变得不可读。 为此目的使用函数!

        switch (i)
        {
            case 1:
                closeToOpen();
                openToClose();

                break;
            case 2:
                openToClose();
                closeToOpen();
        default:
                break;
        }
    }

    void openToClose()
    {
        mediaPlayerElement.Source = null;
        openButton.Content = "Open";
    }

    void closeToOpen()
    {
        FileOpenPicker filePicker = new FileOpenPicker();

        //Add filetype filters.  In this case wmv and mp4.
        filePicker.FileTypeFilter.Add(".wmv");
        filePicker.FileTypeFilter.Add(".mp4");

        filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

        StorageFile file = await filePicker.PickSingleFileAsync();

        if (file != null)
        {
            mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
            mediaPlayerElement.MediaPlayer.Play();
        }

        openButton.Content = "Close";
    }

不确定这是否正是您想要达到的目标,但如果不将其用作指导!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-09
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多