Possible Duplicate:
Finding an enum value by its Description Attribute可能的副本:通过描述属性找到枚举值。
I have a generic extension method which gets the Description
attribute from an Enum
:
我有一个通用的扩展方法,它从枚举中获取描述属性:
enum Animal
{
[Description("")]
NotSet = 0,
[Description("Giant Panda")]
GiantPanda = 1,
[Description("Lesser Spotted Anteater")]
LesserSpottedAnteater = 2
}
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
so I can do...
所以我可以做……
string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
now, I'm trying to work out the equivalent function in the other direction, something like...
现在,我试着算出另一个方向上的等价函数,比如。
Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
6 个解决方案
#1
247
public static class EnumEx
{
public static T GetValueFromDescription<T>(string description)
{
var type = typeof(T);
if(!type.IsEnum) throw new InvalidOperationException();
foreach(var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if(attribute != null)
{
if(attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if(field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");
// or return default(T);
}
}
Usage:
用法:
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
#2
37
rather than extension methods, just try a couple of static methods
只需尝试一些静态方法,而不是扩展方法。
public static class Utility
{
public static string GetDescriptionFromEnumValue(Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
public static T GetEnumValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException();
FieldInfo[] fields = type.GetFields();
var field = fields
.SelectMany(f => f.GetCustomAttributes(
typeof(DescriptionAttribute), false), (
f, a) => new { Field = f, Att = a })
.Where(a => ((DescriptionAttribute)a.Att)
.Description == description).SingleOrDefault();
return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}
}
and use here
这里使用
var result1 = Utility.GetDescriptionFromEnumValue(
Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
"Lesser Spotted Anteater");
#3
12
The solution works good except if you have a Web Service.
除非您有一个Web服务,否则这个解决方案很有用。
You would need to do the Following as the Description Attribute is not serializable.
您需要执行以下操作,因为Description属性不是可序列化的。
[DataContract]
public enum ControlSelectionType
{
[EnumMember(Value = "Not Applicable")]
NotApplicable = 1,
[EnumMember(Value = "Single Select Radio Buttons")]
SingleSelectRadioButtons = 2,
[EnumMember(Value = "Completely Different Display Text")]
SingleSelectDropDownList = 3,
}
public static string GetDescriptionFromEnumValue(Enum value)
{
EnumMemberAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(EnumMemberAttribute), false)
.SingleOrDefault() as EnumMemberAttribute;
return attribute == null ? value.ToString() : attribute.Value;
}
#4
4
Should be pretty straightforward, its just the reverse of your previous method;
应该很简单,它与之前的方法正好相反;
public static int GetEnumFromDescription(string description, Type enumType)
{
foreach (var field in enumType.GetFields())
{
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
if(attribute == null)
continue;
if(attribute.Description == description)
{
return (int) field.GetValue(null);
}
}
return 0;
}
Usage:
用法:
Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));
#5
2
You can't extend Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing method GetDescription
:
您不能将Enum扩展为静态类。您只能扩展类型的实例。考虑到这一点,你需要创建一个静态方法来完成这个;当与您现有的方法GetDescription相结合时,以下内容应该有效:
public static class EnumHelper
{
public static T GetEnumFromString<T>(string value)
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
else
{
string[] enumNames = Enum.GetNames(typeof(T));
foreach (string enumName in enumNames)
{
object e = Enum.Parse(typeof(T), enumName);
if (value == GetDescription((Enum)e))
{
return (T)e;
}
}
}
throw new ArgumentException("The value '" + value
+ "' does not match a valid enum name or description.");
}
}
And the usage of it would be something like this:
它的用法是这样的:
Animal giantPanda = EnumHelper.GetEnumFromString<Animal>("Giant Panda");
#6
0
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
您需要遍历动物的所有枚举值,并返回与您需要的描述相匹配的值。
#1
247
public static class EnumEx
{
public static T GetValueFromDescription<T>(string description)
{
var type = typeof(T);
if(!type.IsEnum) throw new InvalidOperationException();
foreach(var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if(attribute != null)
{
if(attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if(field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");
// or return default(T);
}
}
Usage:
用法:
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
#2
37
rather than extension methods, just try a couple of static methods
只需尝试一些静态方法,而不是扩展方法。
public static class Utility
{
public static string GetDescriptionFromEnumValue(Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
public static T GetEnumValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException();
FieldInfo[] fields = type.GetFields();
var field = fields
.SelectMany(f => f.GetCustomAttributes(
typeof(DescriptionAttribute), false), (
f, a) => new { Field = f, Att = a })
.Where(a => ((DescriptionAttribute)a.Att)
.Description == description).SingleOrDefault();
return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}
}
and use here
这里使用
var result1 = Utility.GetDescriptionFromEnumValue(
Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
"Lesser Spotted Anteater");
#3
12
The solution works good except if you have a Web Service.
除非您有一个Web服务,否则这个解决方案很有用。
You would need to do the Following as the Description Attribute is not serializable.
您需要执行以下操作,因为Description属性不是可序列化的。
[DataContract]
public enum ControlSelectionType
{
[EnumMember(Value = "Not Applicable")]
NotApplicable = 1,
[EnumMember(Value = "Single Select Radio Buttons")]
SingleSelectRadioButtons = 2,
[EnumMember(Value = "Completely Different Display Text")]
SingleSelectDropDownList = 3,
}
public static string GetDescriptionFromEnumValue(Enum value)
{
EnumMemberAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(EnumMemberAttribute), false)
.SingleOrDefault() as EnumMemberAttribute;
return attribute == null ? value.ToString() : attribute.Value;
}
#4
4
Should be pretty straightforward, its just the reverse of your previous method;
应该很简单,它与之前的方法正好相反;
public static int GetEnumFromDescription(string description, Type enumType)
{
foreach (var field in enumType.GetFields())
{
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
if(attribute == null)
continue;
if(attribute.Description == description)
{
return (int) field.GetValue(null);
}
}
return 0;
}
Usage:
用法:
Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));
#5
2
You can't extend Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing method GetDescription
:
您不能将Enum扩展为静态类。您只能扩展类型的实例。考虑到这一点,你需要创建一个静态方法来完成这个;当与您现有的方法GetDescription相结合时,以下内容应该有效:
public static class EnumHelper
{
public static T GetEnumFromString<T>(string value)
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
else
{
string[] enumNames = Enum.GetNames(typeof(T));
foreach (string enumName in enumNames)
{
object e = Enum.Parse(typeof(T), enumName);
if (value == GetDescription((Enum)e))
{
return (T)e;
}
}
}
throw new ArgumentException("The value '" + value
+ "' does not match a valid enum name or description.");
}
}
And the usage of it would be something like this:
它的用法是这样的:
Animal giantPanda = EnumHelper.GetEnumFromString<Animal>("Giant Panda");
#6
0
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
您需要遍历动物的所有枚举值,并返回与您需要的描述相匹配的值。