字符串从字节枚举 [英] String from byte enum
本文介绍了字符串从字节枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有枚举字节值:
enum MarketingEventType : byte {MARKETING_CAMPAIGN, TELESALES, MARKETING_ACTIONS};
我想给所有的元素名称,我将通过ToSting()方法获得。
例如:
I would like to give for all element name, which I will get by ToSting() method. For example:
MarketingEventType.TELESALES.ToString(); // I get "bla bla bla"
MarketingEventType.MARKETING_ACTIONS.ToString(); // I get "la la la"
可能没有从BYTE到STRING的更改类型的枚举
It is possibe without change type of enum from BYTE to STRING?
推荐答案
您不能将枚举类型设置为 string
。有效的基本类型是 byte
, sbyte
, short
, ushort
, int
, uint
,长
和 ulong
。
You can't set an enum type to string
. Valid base types are byte
, sbyte
, short
, ushort
, int
, uint
, long
, and ulong
.
然而,您可以使用描述
属性:
You can, however, use the Description
attribute:
enum MarketingEventType
{
[Description("bla bla bla")]
TELESALES,
}
检索枚举描述是一种混乱,但是您可以使用这种方法(甚至使用扩展方法!):
Retrieving the enum description is kind of a mess, but you can use this method (or even make an extension method out of it!):
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();
}
这篇关于字符串从字节枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文