名前つきの何かを作るための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));
}
}
}