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

Iam*_*ool 3 c# if-statement var

所以目前我这样做:

if(variable == thing1 || variable == thing2 || variable == thing3)
Run Code Online (Sandbox Code Playgroud)

但这不是超级可读的.我想做的是这样的事情:

if(variable == thing1 || thing2 || thing3)
Run Code Online (Sandbox Code Playgroud)

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

Dou*_*las 8

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

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

你可以这样使用它:

if (variable.In(thing1, thing2, thing3))
Run Code Online (Sandbox Code Playgroud)

也就是说,如果被检查的列表不会改变,我宁愿将其声明为静态只读字段,并Contains对此进行调用.上面的扩展方法可能会导致每次调用时都会分配一个新数组,这会影响紧密循环中的性能.

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

public void ProcessThing(Thing variable)
{
    if (_things.Contains(variable))
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果要检查的列表包含多个项目,请使用HashSet<T>替代项.