LoginSignup
45
34

More than 3 years have passed since last update.

C# > enumに文字列を割り当てる。

Last updated at Posted at 2018-07-23

文字列をEnumっぽく使う - Qiitaの続き
Enum数字に文字列を割り当てます。

エラーコードに文字列を割り当てたいときに使いました。

カスタムAttributeの作成

EnumNameAttribute.csをプロジェクト中のお好きな場所に作成
内容は以下

EnumNameAttribute.cs

using System;

namespace Hoge
{

    /// <summary>
    /// Enumに文字列を付加するためのAttributeクラス
    /// </summary>
    public class StringValueAttribute : Attribute
    {
        /// <summary>
        /// Holds the stringvalue for a value in an enum.
        /// </summary>
        public string StringValue { get; protected set; }

        /// <summary>
        /// Constructor used to init a StringValue Attribute
        /// </summary>
        /// <param name="value"></param>
        public StringValueAttribute(string value)
        {
            this.StringValue = value;
        }
    }



    public static class CommonAttribute
    {

        /// <summary>
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetStringValue(this Enum value)
        {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());

            //範囲外の値チェック
            if (fieldInfo == null) return null;

            StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];

            // Return the first if there was a match.
            return attribs.Length > 0 ? attribs[0].StringValue : null;

        }
    }
}

enum定義

以下な感じでenumにStringValueアトリビュートを追加します。

    public enum RESULT_CODE
    {
        [StringValue("正常終了")]
        OK = 0, //正常終了-

        [StringValue("エラー1")]
        ERROR1 = 1, //エラー 1

        [StringValue("エラー2")]
        ERROR2 = 2, //エラー 2
    }

使う

    int response = 1;
    var result = (RESULT_CODE) response;
    var resultString = result.GetStringValue();
45
34
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
34