C#嵌套了具有几乎相似值的if-else优化



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

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);

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

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

switch(%a%variable%here%) {
case %variable%value& {
%code%here%;
break;
}
}

最新更新