【发布时间】:2015-04-20 05:20:16
【问题描述】:
我有以下整数,我想用 if 语句检查它的值。
int myInt = 3;
我尝试了这个有效的代码,但我不喜欢一遍又一遍地写变量名。
if (myInt == 0 || myInt == 2 || myInt == 3 || myInt == 4)
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
为了展示我想要的理想状态,我尝试了这样的方法:
if (myInt == (0 | 2 | 3 | 4))
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
但这不起作用,因为 |不是完全正确的运算符,因为存在类型不匹配。
然后我尝试了这个,它也很好用,但我仍然不喜欢必须声明一个额外的数组。
if ((new int[] { 0, 2, 3, 4 }).Contains(myInt))
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
问题是:
是否有一个运算符可以满足我想要完成的任务,而无需声明额外的数组或使用 || 一遍又一遍地要求相同的变量名运营商?
【问题讨论】:
-
否。 C# 中没有这样的东西。
-
Array.Contains 很好 imo。
-
不声明一个新的数组,不就没有。您可以制作自己的 Extension 方法,但仍会在幕后使用数组。
-
@MarcinJuraszek AFAIK Perl 有 myInt == 1 | 2 | 3 | 4;
-
@JohanLarsson 好吧,这是一个 c# 问题,不是吗? :)
标签: c# arrays if-statement int