将variables与多个值进行比较
经常在我的代码中,我需要比较一个variables的几个值:
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#中有一个更整洁的方法吗?
你可以用.Contains这样做:
 if(new[]{BillType.Receipt,BillType.Bill,BillType.Payment}.Contains(type)){} 
或者,创build自己的扩展方法,使用更易读的语法
 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)){} 
还有switch语句
 switch(type) { case BillType.Bill: case BillType.Payment: case BillType.Receipt: // Do stuff break; } 
假设type是一个枚举,你可以使用FlagsAttribute :
 [Flags] enum BillType { None = 0, Bill = 2, Payment = 4, Receipt = 8 } if ((type & (BillType.Bill | BillType.Payment | BillType.Receipt)) != 0) { //do stuff } 
尝试使用开关
  switch (type) { case BillType.Bill: case BillType.Payment: break; } 
尝试使用C#HashSet的值列表。 如果您需要将许多值与单个值集进行比较,这可能特别有用。
尝试检查策略devise模式(又称策略devise模式)。
 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... } } 
这里有一篇关于如何dynamic解决 Los Techies 政策的文章 。
如何获得所有枚举值的数组,并迭代通过这个?
http://maniish.wordpress.com/2007/09/27/iterate-through-enumeration-c/