(C#) リフレクションを使って定数クラスから定数名を取り出す

フレームワークのエラーコード定義クラスがエラーコードからエラー名を取得するメソッドを用意してくれないときなんかに。

System.Reflection.FieldInfoを使う

FieldInfo.NameとFieldInfo.GetValue()を使って定数名と値を取り出します。

using System;
using System.Collections;
using System.Reflection;

namespace Sample
{
    public class ReflectionConstants
    {
        public static void Main(string[] args)
        {
            Type errorCodeType = typeof(ErrorCode);

            FieldInfo[] infoArray = errorCodeType.GetFields();
            ArrayList tempList = new ArrayList();

            foreach (FieldInfo info in infoArray)
            {
                if (info.FieldType == typeof(Int32))
                {
                    tempList.Add(new ErrorCodeWrapper(info.Name, (int)info.GetValue(info.Name)));
                }
            }

            ReflectionConstants sample = new ReflectionConstants();
            sample.errorCodeList = (ErrorCodeWrapper[]) tempList.ToArray(typeof(ErrorCodeWrapper));
            Array.Sort(sample.errorCodeList, new ErrorCodeComparator());

            if (args.Length != 1)
            {
                Console.WriteLine("Usage: ReflectionConstants [ErrorCode]");
            }
            else
            {
                int errorCode = Int32.Parse(args[0]);
                Console.WriteLine("ErrorName(" + errorCode + ") is " + sample.GetErrorName(errorCode));
            }
        }

        private string GetErrorName(int code)
        {
            string name = "GetErrorName(" + code + ") Not Found!";
            int foundIndex = Array.BinarySearch(errorCodeList, new ErrorCodeWrapper(code), new ErrorCodeComparator());

            if (foundIndex >= 0)
            {
                name = errorCodeList[foundIndex].Name;
            }

            return name;
        }

        private class ErrorCode
        {
            public const int INTERNAL_SERVER_ERROR = 500;
            public const int NOT_IMPLEMENTED = 501;
            public const int BAD_GATEWAY = 502;
            public const int SERVICE_UNAVAILABLE = 503;
            public const int GATEWAY_TIMEOUT = 504;
            public const int HTTP_VERSION_NOT_SUPPORTED = 505;
        }

        private class ErrorCodeWrapper
        {
            public ErrorCodeWrapper(int code) : this("名前がありません", code)
            {
            }
            public ErrorCodeWrapper(string name, int code) : this(name, code, "説明がありません")
            {
            }
            public ErrorCodeWrapper(string name, int code, string reason)
            {
                nameValue = name;
                codeValue = code;
                reasonValue = reason;
            }
            public string Name
            {
                get
                {
                    return nameValue;
                }
            }
            public int Code
            {
                get
                {
                    return codeValue;
                }
            }
            public string Reason
            {
                get
                {
                    return reasonValue;
                }
            }
            private string nameValue;
            private int codeValue;
            private string reasonValue;
        }

        private class ErrorCodeComparator : IComparer
        {
            public int Compare(object x, object y)
            {
                ErrorCodeWrapper a = (ErrorCodeWrapper) x;
                ErrorCodeWrapper b = (ErrorCodeWrapper) y;

                return a.Code.CompareTo(b.Code);
            }
        }

        private ErrorCodeWrapper[] errorCodeList;
    }
}
    

実行結果は次のとおりです。

# ReflectionConstants
Usage: ReflectionConstants [ErrorCode]

# ReflectionConstants 500
ErrorName(500) is INTERNAL_SERVER_ERROR

# ReflectionConstants 501
ErrorName(501) is NOT_IMPLEMENTED

# ReflectionConstants 502
ErrorName(502) is BAD_GATEWAY

# ReflectionConstants 503
ErrorName(503) is SERVICE_UNAVAILABLE

# ReflectionConstants 504
ErrorName(504) is GATEWAY_TIMEOUT

# ReflectionConstants 505
ErrorName(505) is HTTP_VERSION_NOT_SUPPORTED

# ReflectionConstants 506
ErrorName(506) is GetErrorName(506) Not Found!
    

関連情報

Copyright © 2005, AfternoonTea
All rights reserved.