繁体   English   中英

如何在if语句中组合多个OR语句

[英]How to combine many OR statements in an if statement

说这个:

if (stars == 2 || stars ==6 || stars ==10)
{
    do something
}

是否有办法将它们组合在一起,就好像:

if (stars == {2, 4, 6}) <--- MATLAB style
{
       do something
}

你可以这样写一个扩展名:

public static class GenericExtensions
{
    public static bool In<T>(this T @this, params T[] listOfItems)
    {
        if (null == listOfItems) return false;
        return listOfItems.Contains(@this);
    }
}

然后使用它像:

if (2.In(1,2,3,4))

不是语言“MATLAB样式”的一部分,但您可以使用数组和IndexOf

var items = new []{2,4,6};
if(items.IndexOf(stars) > -1)
{
  // do something
}

或类似于Contains

var items = new List<int>{2,4,6};
if(items.Contains(stars))
{
  // do something
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM