地图枚举使用枚举特定的方法函数/动作函数、动作、地图、方法

2023-09-03 13:12:37 作者:互相亏欠

我工作的一个在线预订网站(航空公司),我想验证如果按照某些设置用户/客户的选择的路线是有效的。现有的codeS使用了大量的枚举,我发现自己做的很多,如果/当其它/别的一个特定的枚举映射到,我想发生特定动作。 我想要做的就是写一个枚举特定的方法,会做的映射我。有没有标准的方式来做到这一点?

I'm working on an online booking site (airline) and I want to validate if the user/customer's chosen route is valid according to some settings. The existing codes uses a lot of enums and I found myself doing lots of if/if else/else to map a specific enum to a particular action that I wanted to happen. What I want to do is to write a enum-specific method that would do the mapping for me. Is there any standard way to do this?

下面的的应用程序,code。使用相同的类名/枚举值等,从真正的应用程序的简化版本:

Here's a simplified version of the app code using the same class names/enum values etc from the real app:

// real app has 9 members, shortened for simplicity's sake
public enum RegionType
{
    Station,
    Country,
    All
}

public enum Directionality
{
    Between,
    From,
    To
}

// simplified version
public class Flight
{
     public RegionType RegionType { get; set; }
     public RegionType TravelRegionType { get; set; }
     public string RegionCode { get; set; }
     public string TravelRegionCode { get; set; }
     public string RegionCountryCode { get; set; }
     public string TravelRegionCountryCode { get; set; }
     public Directionality Directionality { get; set; }
}

下面是一些示例用法:

    // valid flight
    Flight flight = new Flight()
    {
        RegionCode = "NY",
        CountryCode = "JP",
        RegionType = RegionType.Station,
        TravelRegionType = RegionType.Country,
        Directionality = Directionality.Between
    };

    // these are the station code/country code that user selected
    // needs to be validated against the Flight object above
    var userSelectedRoutes = new List<KeyValuePair<string, string>>() 
    { 
        new KeyValuePair<string, string>("NY", "JP"),
        new KeyValuePair<string, string>("NY", "AU"),
        new KeyValuePair<string, string>("JP", "NY")
    };

有些code验证我写信,以减少嵌套的if / else的if / else枚举匹配:

Some code validation I wrote to lessen nested if/else if/else enum matching:

private bool IsRouteValid(Directionality direction, string origin, 
                          string destination, string departure, string arrival)
{
    // both departure station and arrival station
    if (direction == Directionality.Between)
    {
        return (origin.Equals(departure, StringComparison.OrdinalIgnoreCase) 
          && destination.Equals(arrival, StringComparison.OrdinalIgnoreCase)
               || origin.Equals(arrival, StringComparison.OrdinalIgnoreCase) 
          && destination.Equals(departure, StringComparison.OrdinalIgnoreCase));
    }
    else if (direction == Directionality.From)
    {
            return (origin.Equals(departure, 
                    StringComparison.OrdinalIgnoreCase));   
    }
    else if (direction == Directionality.To)
    {
            return (destination.Equals(arrival, 
                    StringComparison.OrdinalIgnoreCase));
    }

    return false;
}

和这里的杂乱code我想改变:

And here's the messy code I want to change:

if (flight.RegionType == RegionType.Station 
    && flight.TravelRegionType == RegionType.Country)
{
     return userSelectedRoutes.Any(route => 
            IsRouteValid(flight.Directionality, route.Key, route.Value,
            flight.RegionCode, flight.TravelRegionCode));
}
else if (flight.RegionType == RegionType.Country 
&& flight.TravelRegionType == RegionType.Station)
{
    return userSelectedRoutes.Any(route => 
           IsRouteValid(flight.Directionality, route.Key, route.Value,
           flight.CountryCode, flight.RegionCode));
}
else if (flight.RegionType == RegionType.Station 
&& flight.TravelRegionType == RegionType.Station)
{
    return userSelectedRoutes.Any(route => 
           IsRouteValid(flight.Directionality, route.Key, route.Value,
                       flight.RegionCode, flight.TravelRegionCode));
}
else if (flight.RegionType == RegionType.Station 
&& flight.TravelRegionType == RegionType.All)
{
    return userSelectedRoutes.Any(route => 
           IsRouteValid(flight.Directionality, route.Key, route.Value,
                       flight.RegionCode, route.Value));
}
else if (flight.RegionType == RegionType.All 
&& flight.TravelRegionType == RegionType.Station)
{
    return userSelectedRoutes.Any(route =>
           IsRouteValid(flight.Directionality, route.Key, route.Value,
           route.Key, flight.TravelRegionCode));
}
else if (flight.RegionType == RegionType.All 
        && flight.TravelRegionType == RegionType.All)
{
    return true;
}
else
{
    return false;
} 

注:

区域code =始发站/产地 TravelRegion code =到达站/目的地 =路线必须从给定始发站只有和到达站,反之亦然(例如NY-JP或JP-NY) =从特定电台的任何途径(例如非盟的所有的) =一个特定站点的任何途径(前的所有的-AU)

RegionCode = departure station/origin TravelRegionCode = arrival station/destination Between = routes must be only from the given departure station and arrival station and vice-versa (ex NY-JP or JP-NY) From = from particular station to any routes (ex AU-All) To = any routes to a particular station (ex All-AU)

如果你能注意到,在。任何上述所有条件相同略有改动。我想减少code冗余,如果可能的话。我用 KeyValuePair 所以我有两个出发站和到达站上的一种数据类型。

If you could notice, the .Any of all the conditions above are same with slight changes. I want to reduce code redundancy, if possible. I used KeyValuePair so I have both departure station and arrival station on a single data type.

这是我怎么能做出这样code少凌乱的任何想法/美吗?我知道,我也很难codeD IsRouteValid()但我敢100%肯定方向性只能有的3种可能的组合。 RegionType ,另一方面可能有几个几个的组合就像站,站,站,国家,国家,站,乡村,乡村等。

Any ideas on how could I make this code less messy/beautiful? I know I also hard coded IsRouteValid() but I'm 100% sure that Directionality could only have the 3 possible combinations. RegionType on the other hand could have several several combinations like Station-Station, Station-Country, Country-Station, Country-Country etc.

预计输出:

有效/真正的第一条路线(NY-JP) 无效/假的第二条路线(NY-AU) 有效的/真正的第三条路线(JP-NY),因为方向性]

Valid/True for first route (NY-JP) Invalid/False for second route (NY-AU) Valid/True for third route (JP-NY) [since Directionality is Between]

感谢您阅读这篇提前很长的查询,并感谢您的反馈意见和建议。

Thank you for reading this very long query and thanks in advance for your feedback and suggestions.

类似的帖子:

枚举和字典

推荐答案

一个方法来处理这​​样的枚举动作映射是使用字典。这里有一个例子:

A way to handle such enum-Action-Mappings is using dictionaries. Here's an example:

public enum MyEnum
{
    EnumValue1,
    EnumValue2,
    EnumValue3
}

private IDictionary<MyEnum, Action> Mapping = new Dictionary<MyEnum, Action>
    {
        { MyEnum.EnumValue1, () => { /* Action 1 */ } },
        { MyEnum.EnumValue2, () => { /* Action 2 */ } },
        { MyEnum.EnumValue3, () => { /* Action 3 */ } }
    };

public void HandleEnumValue(MyEnum enumValue)
{
    if (Mapping.ContainsKey(enumValue))
    {
        Mapping[enumValue]();
    }
}

当然你也可以使用 Func键而不是动作处理参数。

编辑:

如果你还没有只使用一个枚举,但对枚举你必须调整上面也许处理元组另一种或方式的例子来汇总枚举值

As you're not only using one enumeration but pairs of enumerations you would have to adjust the example above to maybe handle a Tuple or another way to aggregate the enum values.