枚举实用程序库 [英] Enumeration Utility Library

查看:137
本文介绍了枚举实用程序库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:

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


推荐答案

如果还没有, !您可以从Stackoverflow的其他答案中找到所需的所有方法 - 只需将它们卷入一个项目。以下是一些让您开始的活动:

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:

获取枚举的值说明:

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

这篇关于枚举实用程序库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆