【C#】Enumで文字列定義

便利よね

ってゆかAttirbute便利

こんな感じで定義して

    public enum ApType
    {
        [StringValue("Develop")]
        検品 = 0,
        [StringValue("Production")]
        本番 = 1,
    }

こんな感じで使えるようにしましたぉ

    if (ApType.検品.StringValue() == "Develop")
    {
    }
    else if (ApType.本番.StringValue() == "Production")
    {
    }



まずはAttribute定義

StringValueAttribute.cs

[AttributeUsage(AttributeTargets.Field)]
public sealed class StringValueAttribute : Attribute
{
    public string StringValue { get; private set; }

    public StringValueAttribute(string value)
    {
        StringValue = value;
    }
}



んで、Enumに拡張メソッド定義

EnumExtendor.cs

using System;
using System.Linq;

public static class EnumExtendor
{
    public static string StringValue(this Enum e)
    {
        var fieldInfo = e.GetType().GetField(e.ToString());
        var attribute = (StringValueAttribute)fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false).FirstOrDefault();
        return attribute == null ? null : attribute.StringValue;
    }
}

この例だったら別に普通にToString使ってもいけるんだけどね
列挙子の名前と違う文字列値を定義したいときがあるのよね
例えばパスとか

    if (ApType.検品.ToString() == "検品")
    {
    }
    else if (ApType.本番.ToString() == "本番")
    {
    }