【问题标题】:C# nested if-else optimization with almost similar values具有几乎相似值的 C# 嵌套 if-else 优化
【发布时间】:2020-09-22 20:26:47
【问题描述】:

我有新的用户数据(我想导入/更新它)。通过用户数据查找帐户。 我想根据用户数据找到的帐户更新或创建新帐户 :

            if (accountById != null)
            {
                if (accountByNumber != null)
                {
                    if (accountById.Id == accountByNumber.Id)
                    {
                        if (_isSpecialData)
                        {
                            AddUserDataToAccount(userData, accountByNumber);

                            if (userData.Status == Blocked) return;
                        }
                    }
                    else
                    {
                        _log.Error($"Bad");
                        return;
                    }
                }
                else
                {
                    AddUserDataToAccount(userData, accountById);
                }
            }
            else
            {
                if (accountByNumber != null)
                {
                    if (accountByNumber.RefNo == null)
                    {                            
                        SetAccountAdditionalId(accountByNumber, userData.AdditionalId);

                        if (_isSpecialData)
                        {
                            AddUserDataToAccount(userData, accountByNumber);
                            if (userData.Status == Blocked) return;
                        }
                    }
                    else
                    {
                        _log.Error($"Bad");
                        return;
                    }
                }
                else
                {
                    CreateCardAndProfile2(userData, out createdNewAccount);
                    CreateNewAccount(userData, out createdNewAccount);
                }
            }
                        
            UpdateAccountData(userData, createdNewAccount);

上面的方法可行,但我想知道有没有什么方法可以让它更易读、更优化?

【问题讨论】:

标签: c# .net if-statement optimization nested


【解决方案1】:

您可以使用 switch 运算符,这样您就可以删除许多 if 语句。如果像这样工作: (注意:确保您有一个默认案例和一个中断;在每个案例的末尾)

switch(%a%variable%here%) {

    case %variable%value& {

        %code%here%;
        break;

    }

}

【讨论】:

  • 我看不出,在这种情况下 switch 语句应该如何提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多