【问题标题】:Prevent further execution of calling function in C#防止在 C# 中进一步执行调用函数
【发布时间】:2014-12-25 08:02:09
【问题描述】:

我有一个函数,它在按钮单击时执行,它看起来像这样

private void Login_Button_Click(object sender, RoutedEventArgs e)
    {
        if (!CheckFields())
            return;

        if (!WritePerforceSettingsXml(rewriteSettingsCheckbox.IsChecked.Value))
            return;

        Dictionary<string, string> installerToUpdateList = new Dictionary<string, string>();
        if (!GetUpdateListFilesFromXml(ref installerToUpdateList))
            return;            

       //some code
    }

如您所见,我有一些函数可以检查输入值的正确性,或者里面只有“try-catch”运算符,如果发生“catch”情况或输入无效,调用者的进一步执行(Login_Button_Click 函数)应该被阻止。
但所有返回“bool”的函数都不像我想的那样正确。

还有其他方法可以阻止调用函数进一步执行吗?

【问题讨论】:

  • 函数返回布尔值的具体问题是什么?你只是觉得它看起来很丑?
  • 唯一的选择是在被调用的方法中抛出异常——但这看起来不像这个特定代码的正确方法。所以我认为像你一样使用布尔值很好。
  • 您可以在一个 if 语句中将函数与 || 一起“或”返回。这将与返回 true 的第一个短路,但我认为这看起来不会更好。
  • @KateGregory 不丑,但我不确定我的代码是否正确。我目前正在重构我的代码,如果我将坏代码重构为另一个坏代码,那将毫无价值 XD
  • @juharr 我也有同样的想法,这就是我在这里问这个问题的原因=)

标签: c# function methods


【解决方案1】:

我会反转布尔条件:

private void Login_Button_Click(object sender, RoutedEventArgs e)
{
    if (CheckFields() && WritePerforceSettingsXml(rewriteSettingsCheckbox.IsChecked.Value))
    {
        Dictionary<string, string> installerToUpdateList = new Dictionary<string, string>();
        if (GetUpdateListFilesFromXml(ref installerToUpdateList))
        {         
            //some code
        }
    }
}

通过这种方式,您可以积极地检查哪个更清晰、更容易理解,您还可以减少函数中的数量或返回值,从而提高可读性。该代码的行数也更少。

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2010-11-11
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    相关资源
    最近更新 更多