首页 > 解决方案 > Can I change the use of two ? : shortcuts to use the new switch expression syntax?

问题描述

I have code that looks like this. I wonder if I could replace this with a switch expression type of code:

var ptsMsg1 = !App.cards ?
             "" :
             selectedPoints == pointsCount ?
                " This is the same number as when you started your practice." :
               $" This is {(selectedPoints - pointsCount)} more.";

标签: c#

解决方案


C# 8 switch 表达式可用于:

var msg2 = (App.cards, samePoints: selectedPoints == pointsCount) switch
        {
            { cards: false } => "",
            { samePoints: true } => " This is the same number as when you started your practice.",
            _ => $" This is {(selectedPoints - pointsCount)} more.",
        };

我的回答只是对问题的回应。无论如何,这个或 OP 的代码是否更易于维护是主观的。


推荐阅读