Web140色の一覧を得る方法

Color構造体には定義済みの名前のついた色のリストが存在している。俗にWeb140色というらしい。これを一覧したい場合には次のようにやる。

using System;
using System.Drawing;
using System.Reflection;

namespace garu.ColorList
{
    static class ColorList
    {
        static void Main(string[] args)
        {
            int count = 0;
            foreach (PropertyInfo prop in typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static))
            {
                Color cl = (Color)prop.GetValue(null, null);
                if (cl.Name != "Transparent")
                {
                    string name = cl.Name;
                    int argb = cl.ToArgb();
                    cl = Color.FromArgb(argb);
                    Console.WriteLine("{0:000}:{1}={2}", ++count,
                        ColorTranslator.ToHtml(cl), name);
                }
            }
            Console.ReadLine();
        }
    }
}

見事にWEB色見本 原色大辞典 - HTMLカラーコードに定義されているweb140色のリストが出力される。ちなみに処理中で一回ToArgbを使って色の名前付き情報を消している。こうしないとToHtmlの出力は16進数とならない。


これはReflectionという機能を使っている。たまたまある処理を書くのに必要で調べたのだが、オブジェクトのあらゆるリストが取り出せるので使いこなすと楽しい。