2

.Netで列挙型を操作するためのオープンソースライブラリまたは例を探しています。列挙型(TypeParseなど)に使用される標準の拡張機能に加えて、特定の列挙値のDescription属性の値を返す、またはDescription属性値を持つ列挙値を返すなどの操作を実行する方法が必要です。指定された文字列に一致します。

例えば:

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

2 に答える 2

3

先日、列挙型の代わりにクラスを使用することについて、このブログ投稿を読みました。

http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx

列挙型クラスの基礎として機能する抽象クラスの使用を提案します。基本クラスには、equality、parse、compareなどがあります。

これを使用すると、次のような列挙型のクラスを作成できます(記事から抜粋した例)。

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) { }
}
于 2009-10-22T15:32:25.073 に答える
2

まだない場合は、開始してください。Stackoverflowの他の回答から、必要なすべてのメソッドを見つけることができます。それらを1つのプロジェクトにまとめるだけです。始めるためのいくつかを次に示します。

列挙型の値の取得説明:

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

文字列からnull許容の列挙値を取得する:

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;
    }
}
于 2009-10-22T15:30:36.347 に答える