如何从值获取C#枚举描述? [英] How to get C# Enum description from value?
本文介绍了如何从值获取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 =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
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#中是一个 int
,你可以投掷它。
The default underlying data type for an enum
in C# is an int
, you can just cast it.
这篇关于如何从值获取C#枚举描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文