HIRASE CONNECTION WK

programming collection

目次

Blog 利用状況

ニュース

あわせて読みたいブログパーツ

書庫

日記カテゴリ

Link Collection

[C#] 名前付き定数・・・?

名前つきの何かを作るためのAttribute。

たとえば、下の例のように、表示名だけを変えたいようなケースとか、もう少し拡張すれば、多言語化アプリ作成にも役立ちそう。

using System;
using System.Reflection;

namespace Sample
{
    internal class Program
    {
        enum Windows
        {
            [Name("Windows 95")]
            Chicago,
            [Name("Windows 95 OSR2")]
            Detroit,
            [Name("Windows 98")]
            Memphis,
            [Name("Windows 2000")]
            Cairo,
            [Name("Windows Me")]
            Georgia,
            [Name("Windows XP")]
            Whistler,
            [Name("Windows Vista")]
            Longhorn,
        }

        private static void Main(string[] args)
        {
            foreach (object value in Enum.GetValues(typeof(Windows)))
            {
                String name = NameAttribute.GetName(value as Enum);
                Console.WriteLine(name);
            }
        }
    }

    [AttributeUsage(AttributeTargets.All)]
    public class NameAttribute : Attribute
    {
        public String Name
        {
            get;
            private set;
        }

        public NameAttribute(String name)
        {
            this.Name = name;
        }

        public static String GetName(MemberInfo type)
        {
            Attribute[] attributes;
            attributes = type.GetCustomAttributes(typeof(NameAttribute), true) as Attribute[];
            if (attributes == null || attributes.Length == 0)
                return null;

            NameAttribute nameAttribute = attributes[0] as NameAttribute;
            return nameAttribute.Name;
        }

        public static String GetName(Enum enumValue)
        {
            Type enumType = enumValue.GetType();
            String enumName = Enum.GetName(enumType, enumValue);

            return GetName(enumType.GetField(enumName));
        }
    }
}

投稿日時 : 2008年3月28日 1:01

コメントを追加

# 定数定義クラス その2 2008/03/30 14:27 日々迷走

定数定義クラス その2

# re: [C#] 名前付き定数・・・? 2008/04/01 9:20 T.Hirase

TO: yanさま。
トラックバックどうもです。
ダブってトラックバックされている箇所は消しておきました。

タイトル  
名前  
URL
コメント