使用GOTO在两种情况下切换

时间:2019-03-11 15:59:13

标签: c# uwp switch-statement goto

我想使用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;

1 个答案:

答案 0 :(得分:0)

您应始终避免使用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";
    }

不确定这是否正是您要实现的目标,但是如果没有作为指导!