c#のenumとgenerics
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class TestEnumGenerics{ static N toInt<T, N>( T value ) { return (N) Convert.ChangeType( value, typeof( N ) ); } static T fromInt<T, N>( N value ) { return (T) Enum.ToObject( typeof( T ), value ); } static string toString<T>( T value ) { return value.ToString(); } static T fromString<T>( string value ) { return (T) Enum.Parse( typeof( T ), value ); } static List<T> toList<T>() { return new List<T>( Enum.GetValues( typeof( T ) ) as IEnumerable<T> ); } static void say( string fmt, params object[] args ) { Console.WriteLine( string.Format( fmt, args ) ); } static void test<T>(){ foreach( T value in toList<T>() ) { try { Int64 num = toInt<T,Int64>( value ); T value2 = fromInt<T,Int64>( num ); string str = toString( value ); T value3 = fromString<T>( str ); say( "{0} value={1}/{2}/{3}/{4}/0x{5:x}", typeof( T ).Name, value, value2, value3, str, num ); } catch( OverflowException ) { UInt64 num = toInt<T,UInt64>( value ); T value2 = fromInt<T,UInt64>( num ); string str = toString( value ); T value3 = fromString<T>( str ); say( "{0} value={1}/{2}/{3}/{4}/0x{5:x}", typeof( T ).Name, value, value2, value3, str, num ); } } } enum Enum8 : byte { a, b, c=0xff, }; enum Enum16 : ushort{ a, b, c=0xffff, }; enum Enum32 : uint { a, b, c=0xffffffff, }; enum Enum64 : ulong { a, b, c=0xffffffffffffffffL, }; enum Enum8s : sbyte { a, b, c=-1, }; enum Enum16s : short { a, b, c = -1, }; enum Enum32s : int { a, b, c = -1, }; enum Enum64s : long { a, b, c = -1, }; static void Main( string[] args ) { test<Enum8>(); test<Enum16>(); test<Enum32>(); test<Enum64>(); test<Enum8s>(); test<Enum16s>(); test<Enum32s>(); test<Enum64s>(); } } }
もっとキレイな書き方があればぜひ教えてください。但しVisual Studio 2005で使える範囲で。