将类似的代码拆分成自己的代码?

时间:2018-08-12 19:43:12

标签: c# uwp

我有两个代码块

    private async void AorBButton_Click(object sender, RoutedEventArgs e)
    {
        AuthenticationResult authResult = null;
        ResultText.Text = string.Empty;

        try
        {
            authResult = await App.PublicClientApp.AcquireTokenSilentAsync(scopes, App.PublicClientApp.Users.FirstOrDefault());
        }
        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            try
            {
                authResult = await App.PublicClientApp.AcquireTokenAsync(scopes);
            }
            catch (MsalException msalex)
            {
                ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
            return;
        }

        if (authResult != null)
        {
            // performs one thing or the other thing
        }
    }

因此,如果我单击A按钮,它将遍历所有代码,直到到达最后的if语句并执行一组指令。 如果我按B按钮,它将遍历所有相同的代码,直到到达最后的if语句,但执行一组不同的指令。

我认为我应该能够分解两种情况下完全相同的代码,并从click事件中调用它并运行适当的结果代码。

只是尽我所能地压缩代码。我知道我可以在VBA中做到这一点,但我对如何在C#中实现它并不满意。

1 个答案:

答案 0 :(得分:1)

创建另一个异步方法,执行常用的操作并返回authResult以及一条消息,然后可以将其分配给ResultText.Text。 C#7的值元组可以很方便地返回两个结果。

private async void AorBButton_Click(object sender, RoutedEventArgs e)
{
    var (authResult, message) = await AquireToken();
    ResultText.Text = message;

    if (authResult != null) {
        // performs one thing or the other thing
    }
}

private async Task<(AuthenticationResult authResult, string message)> AquireToken()
{
    AuthenticationResult authResult = null;
    string message = String.Empty;

    try {
        authResult = await App.PublicClientApp.AcquireTokenSilentAsync(scopes, App.PublicClientApp.Users.FirstOrDefault());
    } catch (MsalUiRequiredException ex) {
        // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
        System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

        try {
            authResult = await App.PublicClientApp.AcquireTokenAsync(scopes);
        } catch (MsalException msalex) {
            message = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
        }
    } catch (Exception ex) {
        message = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
    }
    return (authResult, message);
}

在我看来,在Click处理程序中执行所有I / O事情,并在AquireToken方法中执行纯逻辑,而又不依赖于TextBoxes或Labels(ResultText)似乎比较干净。这样,您甚至可以将此逻辑提取到自己的类中。