什么时候应该在 c# if 语句中使用 contains 方法而不是逻辑运算符?

When should I use a contains method instead of logical operators in a c# if statement?

我的同事说我应该在计算枚举时在 if 语句中使用 array.contains()

例子一:

if (new[] { enumvalue.a, enumvalue.b, enumvalue.c }.Contains(x.some_enum_value))
{
    do_something();
}

...与 示例 b:

if (x.some_enum_value == enumvalue.a || x.some_enum_value == enumvalue.b || x.some_enum_value == enumvalue.c) 
{
    do_something();
}

什么时候应该使用示例 a 而不是示例 b?

答案很明确 - 第一个 方法更好 因为它更程序化清洁工

考虑到您的 collection 中有很多物品。因此,将它们全部放在if语句中并编写重复代码会导致多行 if with a lot of or (||) 语句是不好的!

以编程方式意味着您不需要每件事都编写冗长而硬的代码。换句话说,有一种更简洁的方法可以做到这一点。考虑另一个 example.You 不能使用 foreach 循环并自己完成。但这不是一个好方法,因为有一个更简单的方法,那就是使用foreach循环。

C# 7.3 中使用 enum constraint 两全其美:

public static bool IsIn<TEnum>(this TEnum source, params TEnum[] list)
   where TEnum : Enum 
   => list.Contains(source);

或者如果您愿意:

public static bool IsIn<T>(this T source, params T[] list)
   => list.Contains(source);

用法:

var someEnum = MyEnum.Three;

if (someEnum.IsIn(MyEnum.One, MyEnum.Three))
{
   Console.WriteLine();
}

var list = new[]
              {
                 MyEnum.Three,
                 MyEnum.One
              };

if (someEnum.IsIn(list))
{
   Console.WriteLine();
}

注意:总之,你应该做你最喜欢的,最容易维护的,也是你老板喜欢的。其他一切都是主观的。

注2:唯一的优点是扩展方法的使用,它可以使用params关键字获取参数列表。否则,这里面没有太大的价值。