c# - 有没有一种更简洁的方式来检查变量是否是多种事情之一?

c# - 有没有一种更简洁的方式来检查变量是否是多种事情之一?

问题描述:

所以目前我在做这个:c# - 有没有一种更简洁的方式来检查变量是否是多种事情之一?

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

但是,这不是超级可读。我想要做的是这样的:

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

这样的语法是否存在于c#中?

+0

两种语法都存在,但做了完全不同的事情。 –

+1

不要为简短而牺牲清晰度。说了这么多,已经有一些很好的答案了。只要确保首先阅读下一个家伙/加仑更容易,而不是更难。 – pcdev

如果简洁的语法对你很重要,你可以定义一个扩展方法:

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

您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

+0

如果Linq,为什么不包含'Contains'? –

+0

为什么不是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,你当然可以创建一个不太常用的扩展方法。

您有几个选项。

  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(); 
    }