簡體   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