所以目前我在做這個:c# - 有沒有一種更簡潔的方式來檢查變量是否是多種事情之一?
if(variable == thing1 || variable == thing2 || variable == thing3)
但是,這不是超級可讀。我想要做的是這樣的:
if(variable == thing1 || thing2 || thing3)
這樣的語法是否存在於c#中?
所以目前我在做這個:c# - 有沒有一種更簡潔的方式來檢查變量是否是多種事情之一?
if(variable == thing1 || variable == thing2 || variable == thing3)
但是,這不是超級可讀。我想要做的是這樣的:
if(variable == thing1 || thing2 || thing3)
這樣的語法是否存在於c#中?
如果簡潔的語法對你很重要,你可以定義一個擴展方法:
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>
代替。
您cound做:
int[] aux=new int[]{1,2,3};
if(Array.contains(aux, value))
把測試字符串中的列表或數組中,並調用Contains
:
var testers = new [] { "foo1", "foo2" };
if (testers.Contains("subject"))
{
// test succeeded
}
作爲一種替代方案:
if (new [] {"foo1", "foo2"}.Contains("subject"))
{
// test succeeded
}
如果你把把你所有的東西都彙集成某種東西然後是的,你可以用LINQ和Any
https://msdn.microsoft.com/en-us/library/system.linq.enumerable.any(v=vs.110).aspx
如果Linq,爲什麼不包含'Contains'? –
爲什麼不是1,000,000種方法中的任何一種,包括提交替代的代碼? – LoztInSpace
有些人喜歡的擴展方法:
public static bool IsOneOf<T>(this T self, params T[] values) => values.Contains(self);
或相似。
然後你就可以說:
if (variable.IsOneOf(thing1, thing2, thing3))
哎呀,我看道格拉斯是第一個使用這種方法。
它隱式使用默認的相等比較器T
。
缺點是您可以爲所有類型創建擴展方法。如果你只需要它,例如string
,你當然可以創建一個不太常用的擴展方法。
您有幾個選項。
使用switch
(如果thing1
- thing3
是常量表達式)
switch variable
case thing1:
case thing2:
case thing3:
DoSomething();
break;
使用正則表達式(僅適用於字符串)
if (RegEx.Match(variable, "^(thing1|thing2|thing3)"))
{
DoSomething();
}
使用數組
string[] searchFor = new string[] {thing1, thing2, thing3};
if (searchFor.Contains(variable))
{
DoSomething();
}
兩種語法都存在,但做了完全不同的事情。 –
不要爲簡短而犧牲清晰度。說了這麼多,已經有一些很好的答案了。只要確保首先閱讀下一個傢伙/加侖更容易,而不是更難。 – pcdev