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