gpt4 book ai didi

c# - 从描述属性中获取枚举

转载 作者:IT王子 更新时间:2023-10-29 03:29:39 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Finding an enum value by its Description Attribute

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

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;
}

所以我可以...

string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"

现在,我正在尝试从另一个方向计算出等效函数,例如...

Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com