首页 > 解决方案 > 如何在 C# switch 表达式的左侧使用 >=?

问题描述

我有这个枚举:

public enum SIZE
{
    Small = 0,
    Medium = 1,
    Large = 2,
}

我想使用 C# switch 表达式,但我不确定如何创建“case”语句:

App.devWidth = App.width switch
{

};

我想要做的是设置宽度如下:

Small = App.width < 700;
Medium = App.width >= 700 && App.width < 1200;
Large = App.width >= 1200;

有没有办法可以将这些应用程序宽度测试放在开关中“=>”的左侧?

标签: c#c#-8.0

解决方案


如果您使用的是 C# 8.0,则可以使用when如下关键字:

App.devWidth = App.width switch
{
    var x when x >= 0   && x < 700  => SIZE.Small,
    var x when x >= 700 && x < 1200 => SIZE.Medium,
    var x when x >= 1200            => SIZE.Large,
    _   => throw new Exception("Invalid width value")   // if width < 0
};

上面的代码还检查是否App.width >= 0,如果没有则抛出异常(不确定是否需要,但如果不需要,只需删除它)。

在线演示


推荐阅读