C# - IF语句的较短版本

Gap*_*pro 3 c# if-statement

是否有较短版本的IF语句来执行此操作?

if (el.type == ElementType.Type1 || el.type == ElementType.Type2)
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 9

你可以使用扩展方法,但这真的会更好吗?

把它扔在静态类上:

public static bool IsOneOf(this ElementType self, params ElementType[] options)
{
    return options.Contains(self);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

if (el.type.IsOneOf(ElementType.Type1, ElementType.Type2)) {
Run Code Online (Sandbox Code Playgroud)

但是,这将比if语句慢很多,因为有一个隐式数组初始化后跟一个数组遍历,而不是(最多)两个比较和分支.