ユーザーフレンドリーな文字列を持つ Enum ToString 質問する

ユーザーフレンドリーな文字列を持つ Enum ToString 質問する

私の列挙型は次の値で構成されています:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

ただし、これらの値をユーザーフレンドリーな方法で出力できるようにしたいと考えています。
文字列から値に再度移動できる必要はありません。

ベストアンサー1

私はDescriptionSystem.ComponentModel 名前空間の属性。列挙型を装飾するだけです:

private enum PublishStatusValue
{
    [Description("Not Completed")]
    NotCompleted,
    Completed,
    Error
};

次に、このコードを使用して取得します。

public static string GetDescription<T>(this T enumerationValue)
    where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
    {
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
    }

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttribute)attrs[0]).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}

おすすめ記事