简体   繁体   English

检查枚举值 - 替代具有 30 个案例的开关案例?

[英]Checking Enums Values - alternative to a switch case with 30 cases?

I need to find if all conditions fit a certain criteria.我需要确定所有条件是否符合特定标准。

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 has 5 cases:参数有5种情况:

 public enum Parameter: int { Length, Width Height, Area, Volume }

Condition has 6 cases:条件有6种情况:

public enum Condition : int
{
    LessThan,
    LessThanOrEqualTo,
    Equals,
    GreaterThan,
    GreaterThanOrEqualTo,
    DoesNotEqual
}

IN my function I am given an element width height and length and I need to check against OfferServiceConditionDto conditions, paremeters and value.在我的 function 中,我得到了一个元素宽度高度和长度,我需要检查 OfferServiceConditionDto 条件、参数和值。

So far I am only thinking switch cases or ifs but that's a whooping 30 checks.到目前为止,我只考虑 switch case 或 ifs,但那是 30 次检查。

Any better alternative for this?有什么更好的选择吗?

Just extract some methods.只是提取一些方法。 By doing so, you can easily turn 30 (5 * 6) cases into 11 (5 + 6).通过这样做,您可以轻松地将 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM