當前位置: 首頁>>代碼示例>>C#>>正文


C# Enum.HasFlag方法代碼示例

本文整理匯總了C#中System.Enum.HasFlag方法的典型用法代碼示例。如果您正苦於以下問題:C# Enum.HasFlag方法的具體用法?C# Enum.HasFlag怎麽用?C# Enum.HasFlag使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Enum的用法示例。


在下文中一共展示了Enum.HasFlag方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
using System;

[Flags] public enum DinnerItems {
   None = 0,
   Entree = 1,
   Appetizer = 2,
   Side = 4,
   Dessert = 8,
   Beverage = 16, 
   BarBeverage = 32
}

public class Example
{
   public static void Main()
   {
      DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
                            DinnerItems.Beverage | DinnerItems.Dessert;
      DinnerItems flagValue = DinnerItems.Entree | DinnerItems.Beverage;
      Console.WriteLine("{0} includes {1}: {2}", 
                        myOrder, flagValue, myOrder.HasFlag(flagValue));
   }
}
開發者ID:.NET開發者,項目名稱:System,代碼行數:24,代碼來源:Enum.HasFlag

輸出:

Entree, Appetizer, Dessert, Beverage includes Entree, Beverage: True

示例2: Main

//引入命名空間
using System;

[Flags] public enum Pets {
   None = 0,
   Dog = 1,
   Cat = 2,
   Bird = 4,
   Rabbit = 8,
   Other = 16
}

public class Example
{
   public static void Main()
   {
      Pets[] petsInFamilies = { Pets.None, Pets.Dog | Pets.Cat, Pets.Dog };
      int familiesWithoutPets = 0;
      int familiesWithDog = 0;

      foreach (var petsInFamily in petsInFamilies)
      {
         // Count families that have no pets.
         if (petsInFamily.Equals(Pets.None))
            familiesWithoutPets++;
         // Of families with pets, count families that have a dog.
         else if (petsInFamily.HasFlag(Pets.Dog))
            familiesWithDog++;
      }
      Console.WriteLine("{0} of {1} families in the sample have no pets.", 
                        familiesWithoutPets, petsInFamilies.Length);   
      Console.WriteLine("{0} of {1} families in the sample have a dog.", 
                        familiesWithDog, petsInFamilies.Length);   
   }
}
開發者ID:.NET開發者,項目名稱:System,代碼行數:35,代碼來源:Enum.HasFlag

輸出:

1 of 3 families in the sample have no pets.
2 of 3 families in the sample have a dog.


注:本文中的System.Enum.HasFlag方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。