C# 8 switch 表达式:一次处理多个案例? [英] C# 8 switch expression: Handle multiple cases at once?

查看:195
本文介绍了C# 8 switch 表达式:一次处理多个案例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 8 引入了模式匹配,我已经找到了使用它的好地方,比如这个:

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;
    }
}

然后变成

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;
};

然而,你可以看到我现在不得不提到GameType.RoyalBattleGameType.Ffa 两次.有没有办法在模式匹配中一次处理多个案例?我正在考虑这样的事情,但它不是有效的语法:

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;
};

我也尝试过类似的事情

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

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

但没有一个是有效的.

也没有找到任何关于此的示例.它甚至支持吗?

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

推荐答案

你最终可以使用 var 模式 结合 案例保护 (when 子句).不确定它是否比具有重复返回值的变体更好,但它是:

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
};

这篇关于C# 8 switch 表达式:一次处理多个案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆