相关疑难解决方法(0)

将枚举与C#中的字符串相关联

我知道以下是不可能的,因为它必须是一个int

enum GroupTypes
{
    TheGroup = "OEM",
    TheOtherGroup = "CMB"
}
Run Code Online (Sandbox Code Playgroud)

从我的数据库中我得到一个包含不全面代码的字段(OEM和CMB).我想把这个领域变成一个枚举或其他可以理解的东西.因为目标是可读性,所以解决方案应该简洁.
我还有其他选择吗?

.net c#

298
推荐指数
15
解决办法
29万
查看次数

从Description属性获取枚举

可能重复:
通过其描述属性查找枚举值

我有一个通用的扩展方法,它Description从以下方式获取属性Enum:

enum Animal
{
    [Description("")]
    NotSet = 0,

    [Description("Giant Panda")]
    GiantPanda = 1,

    [Description("Lesser Spotted Anteater")]
    LesserSpottedAnteater = 2
}

public static string GetDescription(this Enum value)
{            
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                as DescriptionAttribute;

    return attribute == null ? value.ToString() : attribute.Description;
}
Run Code Online (Sandbox Code Playgroud)

所以我可以......

string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
Run Code Online (Sandbox Code Playgroud)

现在,我正试图在另一个方向上找出等效函数,比如......

Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
Run Code Online (Sandbox Code Playgroud)

.net c# enums attributes

206
推荐指数
4
解决办法
18万
查看次数

标签 统计

.net ×2

c# ×2

attributes ×1

enums ×1