在C#中的if语句中测试多个值 [英] Test for multiple values in an if statement in C#

查看:158
本文介绍了在C#中的if语句中测试多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中是否有简写语法来实现:

Is there a shorthand syntax in C# to make this:

if ((x == 1) || (x==2) || (x==5) || (x==13) || (x==14))

......更短?类似(假设)

... shorter? Something like (hypothetically)

if (x in {1, 2, 5, 13, 14})

我觉得它存在,我只是在精神上和Googly。实际上,我必须经常测试一堆枚举,这是不可读的。如果语言支持,我也讨厌制作一个小帮手功能。

I "feel" like it exists, I'm just coming up short mentally and Googly. In reality I have to test a bunch of enums frequently and it's just unreadable. I also hate to make a little helper function if the language supports it already.

提前致谢!

编辑

有一些涉及列表的聪明解决方案......但我希望有一种纯粹的逻辑结构。如果它不存在,那就这样吧。谢谢!

There are clever solutions involving lists... but I was hoping for a pure logical construct of some kind. If it doesn't exist, so be it. Thanks!

推荐答案

试试这个:

if ((new[]{1, 2, 5, 13, 14}).Contains(x)) ...

这篇关于在C#中的if语句中测试多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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