C# 8 switch expression: Handle multiple cases at once?

℡╲_俬逩灬. 提交于 2020-04-16 19:27:10

问题


C# 8 introduced pattern matching, and I already found good places to use it, like this one:

private static GameType UpdateGameType(GameType gameType)
{
    switch (gameType)
    {
        case GameType.RoyalBattleLegacy:
        case GameType.RoyalBattleNew:
            return GameType.RoyalBattle;
        case GameType.FfaLegacy:
        case GameType.FfaNew:
            return GameType.Ffa;
        default:
            return gameType;
    }
}

which then becomes

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy => GameType.RoyalBattle,
    GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy => GameType.Ffa,
    GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};

However, you can see I now have to mention GameType.RoyalBattle and GameType.Ffa twice. Is there a way to handle multiple cases at once in pattern matching? I'm thinking of anything like this, but it is not valid syntax:

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    GameType.RoyalBattleLegacy, GameType.RoyalBattleNew => GameType.RoyalBattle,
    GameType.FfaLegacy, GameType.FfaNew => GameType.Ffa,
    _ => gameType;
};

I also tried things like

[GameType.RoyalBattleLegacy, GameType.RoyalBattleNew] => GameType.RoyalBattle

or

GameType.FfaLegacy || GameType.FfaNew => GameType.Ffa

but none are valid.

Also did not find any example on this. Is it even supported?


回答1:


You can eventually use var pattern combined with case guard (when clause). Not sure if it is better than the variant with duplicate return values, but here it is:

private static GameType UpdateGameType(GameType gameType) => gameType switch
{
    var v when v == GameType.RoyalBattleLegacy || v == GameType.RoyalBattleNew
        => GameType.RoyalBattle,
    var v when v == GameType.FfaLegacy || v == GameType.FfaNew
        => GameType.Ffa,
    _ => gameType
};


来源:https://stackoverflow.com/questions/56920902/c-sharp-8-switch-expression-handle-multiple-cases-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!