本文介绍了如何从值中获取 C# 枚举描述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的描述属性的枚举:
I have an enum with Description attributes like this:
public enum MyEnum
{
Name1 = 1,
[Description("Here is another")]
HereIsAnother = 2,
[Description("Last one")]
LastOne = 3
}
我发现这段代码用于检索基于枚举的描述
I found this bit of code for retrieving the description based on an Enum
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
if (attributes != null && attributes.Any())
{
return attributes.First().Description;
}
return value.ToString();
}
这允许我编写如下代码:
This allows me to write code like:
var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };
我想要做的是,如果我知道枚举值(例如 1) - 我如何检索描述?换句话说,如何将整数转换为枚举值"以传递给我的 GetDescription 方法?
What I want to do is if I know the enum value (e.g. 1) - how can I retrieve the description? In other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method?
推荐答案
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
C# 中 enum
的默认基础数据类型是 int
,你可以直接转换它.
The default underlying data type for an enum
in C# is an int
, you can just cast it.
这篇关于如何从值中获取 C# 枚举描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!