c# - 如何在 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#);或者
- 通过类似
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 属性包含一个扩展方法来读取属性值。
推荐阅读
- ubuntu - 我的 Nginx 配置是 500 内部服务器错误的罪魁祸首吗?
- makefile - 为什么我的 Makefile 规则没有删除 .o 文件?
- javascript - Node.js 无法导入 ES6 模块
- php - 从输入字段中减去小时和分钟
- django - 更改 SESSION_COOKIE_NAME 后无法登录到 Django 管理员
- c# - Unity Firebase 删除云功能的侦听器
- loops - 启动for循环
- ios - 尝试注销/放松回到主屏幕时,如果甚至没有可选项,为什么会出现 found nil 错误?
- python - 为什么这个点积会给出尺寸错误?
- python - Theano 导入错误/. collect2.exe:错误: