Enum.HasFlag没有按预期工作

时间:2018-03-19 15:11:35

标签: c# enums flags

我有一个带有这样的旗帜的枚举:

[Flags]
public enum ItemType
{
    Shop,
    Farm,
    Weapon,
    Process,
    Sale
}

然后我在列表中有几个对象,其中设置了一些标志并且没有设置一些标志。它看起来像这样:

public static List<ItemInfo> AllItems = new List<ItemInfo>
{
        new ItemInfo{ID = 1, ItemType = ItemType.Shop, Name = "Wasserflasche", usable = true, Thirst = 50, Hunger = 0, Weight = 0.50m, SalesPrice = 2.50m, PurchasePrice = 5,  ItemUseAnimation = new Animation("Trinken", "amb@world_human_drinking@coffee@female@idle_a", "idle_a", (AnimationFlags.OnlyAnimateUpperBody | AnimationFlags.AllowPlayerControl)) },
        new ItemInfo{ID = 2, ItemType = ItemType.Sale, Name = "Sandwich", usable = true, Thirst = 0, Hunger = 50, Weight = 0.5m, PurchasePrice = 10, SalesPrice = 5, ItemUseAnimation = new Animation("Essen", "mp_player_inteat@pnq", "intro", 0) },
        new ItemInfo{ID = 3, ItemType = (ItemType.Shop|ItemType.Process), Name = "Apfel", FarmType = FarmTypes.Apfel, usable = true, Thirst = 25, Hunger = 25, Weight = 0.5m, PurchasePrice = 5, SalesPrice = 2, ItemFarmAnimation = new Animation("Apfel", "amb@prop_human_movie_bulb@base","base", AnimationFlags.Loop)},
        new ItemInfo{ID = 4, ItemType = ItemType.Process, Name = "Brötchen", usable = true, Thirst = -10, Hunger = 40, Weight = 0.5m, PurchasePrice = 7.50m, SalesPrice = 4}
}

然后我带着一个循环进入列表并询问是否设置了标志ItemType.Shop,如下所示:

List<ItemInfo> allShopItems = ItemInfo.AllItems.ToList();
foreach(ItemInfo i in allShopItems)
{
    if (i.ItemType.HasFlag(ItemType.Shop))
    {
        API.consoleOutput(i.Name);
    }
}

这是我的循环的输出 - 它显示列表中的所有项目,.HasFlag方法在这种情况下始终返回true。

Wasserflasche
Sandwich
Apfel
Brötchen

2 个答案:

答案 0 :(得分:4)

尝试为枚举值

指定值
[Flags]
public enum ItemType 
{
    Shop = 1,
    Farm = 2,
    Weapon = 4,
    Process = 8,
    Sale = 16
}

以下是部分 Guidelines for FlagsAttribute and Enum(摘自Microsoft Docs)

  • 仅当对数值执行按位运算(AND,OR,EXCLUSIVE OR)时,才使用FlagsAttribute自定义属性进行枚举。
  • 以2的幂为单位定义枚举常量,即1,2,4,8等。这意味着组合枚举常量中的各个标志不重叠。

答案 1 :(得分:1)

您应该为您的枚举分配值。所有flags属性都会改变ToString方法的工作方式。我会使用按位运算符来减少错误:

[Flags]
public enum ItemType
{
    Shop = 1 << 0, // == 1
    Farm = 1 << 1, // == 2
    Weapon = 1 << 2, // == 4
    Process = 1 << 3, // == 8
    Sale = 1 << 4 // == 16
}