本文整理汇总了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));
}
}
输出:
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);
}
}
输出:
1 of 3 families in the sample have no pets. 2 of 3 families in the sample have a dog.