ReSharper 并删除多余的括号。 C# 中的 OR 与 AND 逻辑
ReSharper and remove redundant parentheses. OR vs AND logic in C#
我最近注意到 ReSharper (2016.3) 现在说要删除 C# 语句中的冗余括号,我相信这会导致预期行为发生变化。是这样的说法吗:
private bool GetAutoAdjust( int catType )
{
return ( catType == ChargeTypeIds.Penalty && _appSettingRepository.AutoRemovePen ) ||
( catType == ChargeTypeIds.Interest && _appSettingRepository.AutoRemoveInt ) ||
( catType == ChargeTypeIds.Discount && _appSettingRepository.AutoRemoveDis );
}
真的相当于这个吗?
private bool GetAutoAdjust( int catType )
{
return catType == ChargeTypeIds.Penalty && _appSettingRepository.AutoRemovePen ||
catType == ChargeTypeIds.Interest && _appSettingRepository.AutoRemoveInt ||
catType == ChargeTypeIds.Discount && _appSettingRepository.AutoRemoveDis ;
}
也许我在 C# 计算 OR 子句的方式与 SQL Server 之类的东西相比是错误的,但不会对表达式的左侧和右侧进行 OR 计算,或者不计算表达式实际上在评估 OR 条件之前预先连接所有 AND 条件?
在 C# 中,运算符有一个优先顺序。从 the docs 您可以看到 &&
出现在 ||
之前,所以从技术上讲 Resharper 是正确的,那些括号是多余的。
话虽如此,如果您觉得保留它们更明显 - 然后保留它们。代码的可读性应始终是优先事项。
我最近注意到 ReSharper (2016.3) 现在说要删除 C# 语句中的冗余括号,我相信这会导致预期行为发生变化。是这样的说法吗:
private bool GetAutoAdjust( int catType )
{
return ( catType == ChargeTypeIds.Penalty && _appSettingRepository.AutoRemovePen ) ||
( catType == ChargeTypeIds.Interest && _appSettingRepository.AutoRemoveInt ) ||
( catType == ChargeTypeIds.Discount && _appSettingRepository.AutoRemoveDis );
}
真的相当于这个吗?
private bool GetAutoAdjust( int catType )
{
return catType == ChargeTypeIds.Penalty && _appSettingRepository.AutoRemovePen ||
catType == ChargeTypeIds.Interest && _appSettingRepository.AutoRemoveInt ||
catType == ChargeTypeIds.Discount && _appSettingRepository.AutoRemoveDis ;
}
也许我在 C# 计算 OR 子句的方式与 SQL Server 之类的东西相比是错误的,但不会对表达式的左侧和右侧进行 OR 计算,或者不计算表达式实际上在评估 OR 条件之前预先连接所有 AND 条件?
在 C# 中,运算符有一个优先顺序。从 the docs 您可以看到 &&
出现在 ||
之前,所以从技术上讲 Resharper 是正确的,那些括号是多余的。
话虽如此,如果您觉得保留它们更明显 - 然后保留它们。代码的可读性应始终是优先事项。