我需要查找是否所有条件都符合某个标准。
public class OfferServiceConditionDto
{
public long Id { get; set; }
public Parameter Parameter { get; set; }
public Enums.Condition Condition { get; set; }
public double? Value { get; set; }
[JsonIgnore]
public long? OfferSubServiceId { get; set; }
}
Parameters有5种情况。
public enum Parameter : int { Length, Width Height, Area, Volume }
Condition有6种情况。
public enum Condition : int
{
LessThan,
LessThanOrEqualTo,
Equals,
GreaterThan,
GreaterThanOrEqualTo,
DoesNotEqual
}
在我的函数中,我给了一个元素宽度高度和长度,我需要检查OfferServiceConditionDto条件,参数和值。
到目前为止,我只考虑到开关情况或ifs,但这是一个惊人的30次检查。
有什么更好的选择吗?
只要提取一些方法即可。通过这样做,你可以很容易地把30(5*6)个案例变成11(5+6)个。
public static bool CheckCondition(double width, double height, double length, OfferServiceConditionDto dto) {
switch (dto.Parameter) {
case Parameter.Length:
return CheckCondition(dto.Condition, length, dto.Value);
case Parameter.Height:
return CheckCondition(dto.Condition, height, dto.Value);
// plus 3 more...
}
return false;
}
private static bool CheckCondition(Enums.Condition condition, double value1, double? value2) {
if (value2 == null) {
return true; // decide what to do if Value is null
}
switch (condition) {
case Enums.Condition.LessThan:
return value1 < value2.Value;
case Enums.Condition.LessThanOrEqualTo:
return value1 <= value2.Value;
// plus 4 more...
}
return false;
}