c# - 如何在 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# 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
,如果没有则抛出异常(不确定是否需要,但如果不需要,只需删除它)。
推荐阅读
- flutter - android studio 中存在错误,但在 flutlab.io 上工作的代码相同
- python - 如何在python中以year-mon格式获取最后三个月?
- python - 嵌套列表中的重复值
- python - 如何根据给定值删除列中的项目?
- amazon-web-services - Docker容器之间的Laravel中的Redis连接问题
- c++ - 将字符输入到 int 变量中
- google-sheets - 列作为维度的动态范围
- html - 为什么我的当我添加另一个元素时被推到我的标题下?
- c++ - 我们可以在 c++ 的 main 函数中声明一个向量作为模板吗,如果可以的话怎么做?
- javascript - Chrome 是否停止支持 Intl 功能?