Dav*_*avy 1 c# enums attributes
我通常访问枚举描述以获得相应的值,例如:
Enum.GetName(typeof(MyEnum),myid);
我需要一个可以使用任何字符的枚举,例如"hello world%^ $£%&"
我见过有人附加属性并添加扩展名,如下所示:
http://weblogs.asp.net/stefansedich/archive/2008/03/12/enum-with-string-values-in-c.aspx
但如果可以用来访问长描述,我无法解决.
有人做过类似的事吗?
谢谢
戴维
为什么不能解决问题呢?
您可以通过从属性中继承来创建自己的属性
public class EnumInformation: Attribute
{
public string LongDescription { get; set; }
public string ShortDescription { get; set; }
}
public static string GetLongDescription(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
EnumInformation [] attribs = fieldInfo.GetCustomAttributes(
typeof(EnumInformation ), false) as EnumInformation [];
// Return the first if there was a match.
return attribs != null && attribs.Length > 0 ? attribs[0].LongDescription : null;
}
public static string GetShortDescription(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
EnumInformation [] attribs = fieldInfo.GetCustomAttributes(
typeof(EnumInformation ), false) as EnumInformation [];
// Return the first if there was a match.
return attribs != null && attribs.Length > 0 ? attribs[0].ShortDescription : null;
}
Run Code Online (Sandbox Code Playgroud)
你的Enum看起来像这样
public enum MyEnum
{
[EnumInformation(LongDescription="This is the Number 1", ShortDescription= "1")]
One,
[EnumInformation(LongDescription = "This is the Number Two", ShortDescription = "2")]
Two
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它
MyEnum test1 = MyEnum.One;
Console.WriteLine("test1.GetLongDescription = {0}", test1.GetLongDescription());
Console.WriteLine("test1.GetShortDescription = {0}", test1.GetShortDescription());
Run Code Online (Sandbox Code Playgroud)
它输出
test1.GetLongDescription =这是数字1
test1.GetShortDescription = 1
您实际上可以向属性添加属性以获取各种信息.然后,您可以支持您正在寻找的本地化.