代码之家  ›  专栏  ›  技术社区  ›  Mongus Pong

将变量与多个值进行比较[重复]

c#
  •  44
  • Mongus Pong  · 技术社区  · 16 年前

    if ( type == BillType.Bill || type == BillType.Payment || type == BillType.Receipt )
    {
      // Do stuff
    }
    

    我一直在想我能做到:

    if ( type in ( BillType.Bill, BillType.Payment, BillType.Receipt ) )
    {
       // Do stuff
    }
    

    但这当然是SQL允许的。

    在C#有更整洁的方式吗?

    7 回复  |  直到 16 年前
        1
  •  77
  •   Mark    16 年前

    if(new[]{BillType.Receipt,BillType.Bill,BillType.Payment}.Contains(type)){}
    

    public static class MyExtensions
    {
        public static bool IsIn<T>(this T @this, params T[] possibles)
        {
            return possibles.Contains(@this);
        }
    }
    

    然后通过以下方式进行调用:

    if(type.IsIn(BillType.Receipt,BillType.Bill,BillType.Payment)){}
    
        2
  •  11
  •   wasatz    16 年前

    还有switch语句

    switch(type) {
        case BillType.Bill:
        case BillType.Payment:
        case BillType.Receipt:
            // Do stuff
            break;
    }
    
        3
  •  9
  •   Yuriy Faktorovich    16 年前

    假设类型是枚举,则可以使用 FlagsAttribute

    [Flags]
    enum BillType
    {
        None = 0,
        Bill = 2,
        Payment = 4,
        Receipt = 8
    }
    
    if ((type & (BillType.Bill | BillType.Payment | BillType.Receipt)) != 0)
    {
        //do stuff
    }
    
        4
  •  3
  •   bleeeah    16 年前

    尝试使用开关

     switch (type)
        {
            case BillType.Bill:
            case BillType.Payment:
    
            break;
        }
    
        5
  •  0
  •   Sergiy Belozorov Mohaiminul Islam    16 年前

    尝试对值列表使用C#HashSet。如果需要将多个值与单个值集进行比较,则这一点尤其有用。

        6
  •  0
  •   Jarrett Meyer    16 年前

    尝试查看策略设计模式(也称策略设计模式)。

    public interface IBillTypePolicy
    {
        public BillType { get; }
        void HandleBillType();
    }
    public class BillPolicy : IBillTypePolicy
    {
        public BillType BillType { get { return BillType.Bill; } }
    
        public void HandleBillType() 
        { 
            // your code here...
        }
    }
    

    这里有一个 great post on how to dynamically resolve the policy