我正在寻找一个开源库或用于在.Net中使用Enum类型的示例。除了人们用于枚举的标准扩展(TypeParse等)之外,我还需要一种方法来执行操作,例如返回给定枚举值的Description属性的值或返回具有Description属性值的枚举值匹配给定的字符串。

例如:

//if extension method
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican
//and
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA"
有帮助吗?

解决方案

如果还没有,请开始一个!您可以在Stackoverflow上找到其他答案所需的所有方法 - 只需将它们滚动到一个项目中即可。这里有一些可以帮助您入门:

获取枚举值说明:

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;
}

从字符串中获取可枚举的枚举值:

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;
    }
}

其他提示

我前几天阅读了这篇关于使用类而不是枚举的帖子:

http://www.lostechies的.com /博客/ jimmy_bogard /存档/ 2008/08/12 /枚举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) { }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top