在 C# 中的 if 语句中测试多个值 [英] Test for multiple values in an if statement in C#
本文介绍了在 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})
我感觉"它存在,我只是在精神上和谷歌上表现不佳.实际上,我必须经常测试一堆枚举,而且它只是不可读.如果语言已经支持它,我也讨厌创建一个小辅助函数.
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屋!
查看全文