问题
I'm looking for a open source library or examples for working with Enum types in .Net. In addition to the standard extensions that people use for Enums (TypeParse, etc.), I need a way to perform operations like returning the value of the Description attribute for a given enumeration value or to return a enumeration value that has a Description attribute value that matches a given string.
For example:
//if extension method
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican
//and
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA"
回答1:
If there isn't one already, start one! You can probably find all the methods you need from other answers here on Stackoverflow - just roll them into one project. Here's a few to get you started:
Getting value of enum Description:
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), true));
if(attribs.Length > 0)
{
return ((DescriptionAttribute)attribs[0]).Description;
}
return string.Empty;
}
Getting a nullable enum value from string:
public static class EnumUtils
{
public static Nullable<T> Parse<T>(string input) where T : struct
{
//since we cant do a generic type constraint
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Generic Type 'T' must be an Enum");
}
if (!string.IsNullOrEmpty(input))
{
if (Enum.GetNames(typeof(T)).Any(
e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
{
return (T)Enum.Parse(typeof(T), input, true);
}
}
return null;
}
}
回答2:
I read this blog post the other day about using classes instead of enums:
http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx
Proposes the use of an abstract class to serve as the basis of enum classes. Base class has things like equality, parse, compare, etc.
Using it, you can have classes for your enums like this (example taken from article):
public class EmployeeType : Enumeration
{
public static readonly EmployeeType Manager
= new EmployeeType(0, "Manager");
public static readonly EmployeeType Servant
= new EmployeeType(1, "Servant");
public static readonly EmployeeType AssistantToTheRegionalManager
= new EmployeeType(2, "Assistant to the Regional Manager");
private EmployeeType() { }
private EmployeeType(int value, string displayName) : base(value, displayName) { }
}
来源:https://stackoverflow.com/questions/1608000/enumeration-utility-library