首页 > 解决方案 > 如何在 C# 中枚举类型的每个枚举值上添加元数据信息?

问题描述

我想要一个带有扩展数据的枚举值列表。数据库只会保存与我的枚举值相对应的整数值,但在代码中,我希望获得的信息不仅仅是枚举名称。

让我给你举个例子:

public enum Reason
{
    NotEnoughStock, // Valid = yes, Responsability = company, Text = There is not enough stock
    ProductNotAvailabe, // Valid = no, Responsability = company, Text = Produc is not available
    PaymentNotDone, // Valid = no, Responsability = client, Text = Payment is not done
    BlackListedClient, // Valid = no, Responsability = client, Text = Client is black listed
    NotEnoughTime // Valid = yes, Responsability = company, Text = There is not enough time
}

我怎样才能做到这一点?我应该使用枚举以外的东西吗?我喜欢枚举。

标签: c#enumsmetadata

解决方案


你可以:

  • 使用属性(C#);或者
  • 通过类似Helper.GetExtraInfo(MyType val).

对于“文本”值,您可以使用DescriptionAttribute。对于其他两个,我认为您应该创建新属性。

class ValidAttribute : Attribute
{
    public bool Valid { get; private set; }

    public ValidAttribute(bool valid)
    {
        this.valid = valid;
    }
}

Get enum from enum 属性包含一个扩展方法来读取属性值。


推荐阅读