c# - Enum.HasFlag 未按预期工作

标签 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

最佳答案

尝试为您的枚举赋值

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

这里有一些 Guidelines for FlagsAttribute and Enum (摘自微软文档)

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

关于c# - Enum.HasFlag 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49366272/

相关文章:

c# - 为什么我在编码网站上看到的大多数 DataContract 的 DataMembers 不是使用自动属性编写的?

c++ - 在 C++ 中使用 #define 定义位标志

c - 这是验证菜单的好习惯吗?

c# - 从一组枚举值中选择

java - 将 Map<Enum, Enum> 存储为字符串

java - REGEX 从控制台命令获取标志?

C# 任务调度器查询

c# - 写一个C#脚本测试上百个域名

c# - 如何在 C# 中使用 Windows 搜索服务

python - 如何整理参数功能以从枚举创建一组值?