c# - 是否有一种更简洁的方法来检查变量是否是多个变量之一?

c# - is there a terser way to check if a variable is one of multiple things?

所以我目前正在这样做:

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

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

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

c#中有这样的语法吗?

你可以这样做:

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

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

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>

有些人更喜欢扩展方法:

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

我觉得这很不错。如果变量 = 479 或 482 或 1482 等

if (new int[] { 479, 482, 1482, 2760 }.Contains(variable))
{
    DoSomething();
}