0

説明属性による列挙値の検索の重複の可能性

ユーザーが選択したチェックボックスからMyEnumの説明を取得します。値を見つけて、保存する必要があります。誰かが説明された列挙型の値を見つける方法を教えてもらえますか

public enum MyEnum
{
   [Description("First One")]
   N1,
   [Description("Here is another")]
   N2,
   [Description("Last one")]
   N3
}

たとえば、Here is AnotherはN1を返さなければなりません。最後の1つを受け取ったら、N3を返さなければなりません。

値からC#列挙型の説明を取得する方法の反対を行う必要がありますか?

誰かが私を助けることができますか?

4

1 に答える 1

1

このような:

// 1. define a method to retrieve the enum description
public static string ToEnumDescription(this Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

//2. this is how you would retrieve the enum based on the description:
public static MyEnum GetMyEnumFromDescription(string description)
{
    var enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();

    // let's throw an exception if the description is invalid...
    return enums.First(c => c.ToEnumDescription() == description);
}

//3. test it:
var enumChoice = EnumHelper.GetMyEnumFromDescription("Third");
Console.WriteLine(enumChoice.ToEnumDescription());
于 2012-04-12T15:53:10.317 に答える