【问题标题】:Enumeration Utility Library枚举实用程序库
【发布时间】:2009-10-22 15:24:32
【问题描述】:

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

例如:

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

【问题讨论】:

标签: .net enums enumeration


【解决方案1】:

前几天我读到了这篇关于使用类而不是枚举的博文:

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) { }
}

【讨论】:

  • 谢谢俏皮话。这篇文章提出了一些与我的情况相关的非常好的观点。
【解决方案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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多