我正在寻找一个开源库或用于在.Net中使用Enum类型的示例。除了人们用于枚举的标准扩展(TypeParse等)之外,我还需要一种方法来执行操作,例如返回给定枚举值的Description属性的值或返回具有Description属性值的枚举值匹配给定的字符串。
例如:
//if extension method
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican
//and
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA"
答案 0 :(得分:3)
我前几天阅读了这篇关于使用类而不是枚举的帖子:
http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx
建议使用抽象类作为枚举类的基础。基类具有相等,解析,比较等内容。
使用它,你可以拥有这样的枚举类(例子来自文章):
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) { }
}
答案 1 :(得分:2)
如果还没有,请开始一个!您可以在Stackoverflow上找到其他答案所需的所有方法 - 只需将它们滚动到一个项目中即可。这里有一些可以帮助您入门:
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;
}
}