本文翻译自:How to get C# Enum description from value? [duplicate]
Possible Duplicate: 可能重复:
Getting attributes of Enum's value 获取枚举值的属性
I have an enum with Description attributes like this: 我有一个带有Description属性的枚举,如下所示:
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) };
What I want to do is if I know the enum value (eg 1) - how can I retrieve the description? 我想做的是,如果我知道枚举值(例如1)-如何获取描述? In other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method? 换句话说,如何将整数转换为“ Enum值”以传递给我的GetDescription方法?
#1楼
参考:https://stackoom.com/question/B7PE/如何从值获取C-枚举描述-重复
#2楼
I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects: 我通过通用扩展方法将代码与可接受的答案放在一起,因此可以用于各种对象:
public static string DescriptionAttr<T>(this T source)
{
FieldInfo fi = source.GetType().GetField(source.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) return attributes[0].Description;
else return source.ToString();
}
Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this: 使用原始帖子中的枚举,或使用属性用Description属性修饰的任何其他类,可以像下面这样使用代码:
string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();
#3楼
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it. C#中enum
的默认基础数据类型是int
,您可以将其强制转换。
#4楼
You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. 您无法轻松地以通用方式执行此操作:您只能将整数转换为特定类型的枚举。 As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. 正如Nicholas所展示的,如果只关心一种枚举,这是一个琐碎的转换,但是如果您想编写一个可以处理不同种类的枚举的通用方法,事情就会变得更加复杂。 You want a method along the lines of: 您需要以下方法:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)((TEnum)value)); // error!
}
but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). 但这会导致编译器错误“无法将int转换为TEnum”(如果解决此问题,则将导致“无法将TEnum转换为Enum”)。 So you need to fool the compiler by inserting casts to object: 因此,您需要通过将强制类型转换插入对象来愚弄编译器:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)(object)((TEnum)(object)value)); // ugly, but works
}
You can now call this to get a description for whatever type of enum is at hand: 现在,您可以调用此命令以获取有关手头类型的描述:
GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);
#5楼
Update 更新资料
The Unconstrained Melody library is no longer maintained; 无约束的旋律库不再维护; Support was dropped in favour of Enums.NET . 对Enums.NET的支持被放弃了。
In Enums.NET you'd use: 在Enums.NET中,您将使用:
string description = ((MyEnum)value).AsString(EnumFormat.Description);
Original post 原始帖子
I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use: 我在“ 不受约束的旋律”中以一种通用的,类型安全的方式实现了这一点-您可以使用:
string description = Enums.GetDescription((MyEnum)value);
This: 这个:
- Ensures (with generic type constraints) that the value really is an enum value 确保(具有通用类型约束)该值确实是一个枚举值
- Avoids the boxing in your current solution 避免当前解决方案中的装箱
- Caches all the descriptions to avoid using reflection on every call 缓存所有描述,以避免在每次调用时使用反射
- Has a bunch of other methods, including the ability to parse the value from the description 还有很多其他方法,包括从描述中解析值的能力
I realise the core answer was just the cast from an int
to MyEnum
, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :) 我知道核心答案只是从int
到MyEnum
,但是如果您要进行大量枚举工作,则值得考虑使用Unconstrained Melody :)
#6楼
To make this easier to use, I wrote a generic extension: 为了使它更易于使用,我编写了一个通用扩展名:
public static string ToDescription<TEnum>(this TEnum EnumValue) where TEnum : struct
{
return Enumerations.GetEnumDescription((Enum)(object)((TEnum)EnumValue));
}
now I can write: 现在我可以写:
MyEnum my = MyEnum.HereIsAnother;
string description = my.ToDescription();
System.Diagnostics.Debug.Print(description);
Note: replace "Enumerations" above with your class name 注意:用您的班级名称替换上面的“枚举”