2017-10-15 121 views
3

所以目前我在做這個:c# - 有沒有一種更簡潔的方式來檢查變量是否是多種事情之一?

if(variable == thing1 || variable == thing2 || variable == thing3) 

但是,這不是超級可讀。我想要做的是這樣的:

if(variable == thing1 || thing2 || thing3) 

這樣的語法是否存在於c#中?

+0

兩種語法都存在,但做了完全不同的事情。 –

+1

不要爲簡短而犧牲清晰度。說了這麼多,已經有一些很好的答案了。只要確保首先閱讀下一個傢伙/加侖更容易,而不是更難。 – pcdev

回答

8

如果簡潔的語法對你很重要,你可以定義一個擴展方法:

public static class ObjectExtensions 
{ 
    public static bool In<T>(this T item, params T[] elements) 
    { 
     return elements.Contains(item); 
    } 
} 

然後,您可以使用此像這樣:

if (variable.In(thing1, thing2, thing3)) 

也就是說,如果被檢查的列表不會改變,我寧願將其聲明爲靜態只讀字段,並且針對該字段調用Contains。上面的擴展方法可能會導致每次調用時分配一個新的數組,這可能會在緊密循環中損害性能。

private static readonly Thing[] _things = new [] { thing1, thing2, thing3 }; 

public void ProcessThing(Thing variable) 
{ 
    if (_things.Contains(variable)) 
    { 
     // ... 
    } 
} 

而且,如果對被檢查的列表中包含多了幾個項目,使用HashSet<T>代替。

+1

Oww ...很好的語法...就像OP問:-) – Stefan

+0

是否有這樣的理由讓OP的僞代碼不被允許? –

+0

@CamiloTerevinto:這是一個語言設計問題。有一些需要考慮的因素,例如類型轉換,短路,操作員關聯性等。如果有的話,我更傾向於使用類似於上面的擴展方法的'in'關鍵字來使用類似SQL的語法。 – Douglas

1

您cound做:

int[] aux=new int[]{1,2,3}; 
if(Array.contains(aux, value)) 
3

把測試字符串中的列表或數組中,並調用Contains

var testers = new [] { "foo1", "foo2" }; 

if (testers.Contains("subject")) 
{ 
    // test succeeded 
} 

作爲一種替代方案:

if (new [] {"foo1", "foo2"}.Contains("subject")) 
{ 
    // test succeeded 
} 
2

有些人喜歡的擴展方法:

public static bool IsOneOf<T>(this T self, params T[] values) => values.Contains(self); 

或相似。

然後你就可以說:

if (variable.IsOneOf(thing1, thing2, thing3)) 

哎呀,我看道格拉斯是第一個使用這種方法。

它隱式使用默認的相等比較器T

缺點是您可以爲所有類型創建擴展方法。如果你只需要它,例如string,你當然可以創建一個不太常用的擴展方法。

0

您有幾個選項。

  1. 使用switch(如果thing1 - thing3是常量表達式)

    switch variable 
        case thing1: 
        case thing2: 
        case thing3: 
         DoSomething(); 
         break; 
    
  2. 使用正則表達式(僅適用於字符串)

    if (RegEx.Match(variable, "^(thing1|thing2|thing3)")) 
    { 
        DoSomething(); 
    } 
    
  3. 使用數組

    string[] searchFor = new string[] {thing1, thing2, thing3}; 
    if (searchFor.Contains(variable)) 
    { 
        DoSomething(); 
    } 
    
相關問題