c# - 通过枚举匹配类

标签 c# class enums

您好,我有一个抽象类 Item。 Food、Weapon 等类继承自该类。有关此项目的所有信息都存储在数据库中,C# 代码的工作是匹配确切的类并通过 Enum 匹配它,它也作为整数存储在数据库列中。我的问题是这个愚蠢的代码,无论我必须使用食物、武器等类的方法

if ((ItemType)userItem.ItemType == ItemType.Food)
{
    Food food = new Food(userItem);
    food.UseItem(sender);
}
else if ((ItemType)userItem.ItemType == ItemType.Weapon)
{
    Weapon weapon = new Weapon(userItem);
    weapon.UseItem(sender);
}

在食物、武器等类的构造函数的参数中是来自数据库的对象,让对象了解其字段。

是否有某种东西可以帮助我在没有这段代码的情况下匹配这种类型?当我看着它时,我真的很烦。

最佳答案

您可以使用工厂或创建方法来创建特定类型的项目:

public Item CreateItem(UserItem userItem)
{
    var itemType = (ItemType)userItem.ItemType;
    switch(itemType)
    {
        case ItemType.Food: return new Food(userItem);
        case ItemType.Weapon: return new Weapon(userItem);
        // etc
        default:
            throw new NotSupportedException($"Item type {itemType} is not supported");
    }
}

然后使用此方法创建项目并使用它们。例如。您当前的代码将如下所示:

var item = CreateItem(userItem);
item.UseItem(sender); // you don't care about specific type of item

注意:EF 可以使用 discriminator 列自动创建适当类型的实体。

关于c# - 通过枚举匹配类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43525367/

相关文章:

c# - 类名周围的括号在 C# 类中意味着什么

objective-c - Objective-C 的命名空间约定

java - 无法在被映射的枚举的初始值设定项内构造 EnumMap

c# - 如何在 C# 中解密用 GO 语言加密的 RSA 加密字符串。解码 OAEP 填充时出错

c# - Entity Framework 等效于ADO.Net的DataRow.HasErrors?

c# - NLog 不创建日志文件

python - 如何从元组列表中创建变量并将其设置为类?

python - 如何在Python中创建一个类来下载文件

swift - 如何定义特定类型的间接枚举情况

c++ - |= 和 &= 是如何工作的?