概要
var x = new List<int>(); var y = new Dictionary<int, string>(); print( x.GetType().Name ); // List`1 print( y.GetType().Name ); // Dictionary`2
型情報をType.GetType()
で取得して Type.Name
を参照することで
型の名前を表す文字列が取得可能ですが、ジェネリッククラスの場合、
何が型引数に指定されているのかが不明です
下記の拡張メソッドを使用することで
何が型引数に指定されているのかを文字列で取得可能になります
using System; using System.Linq; public static class TypeExtensions { public static string GetGenericName( this Type self ) { if ( !self.IsGenericType ) { return self.Name; } return string.Format( "{0}<{1}>", self.Name.Split( '`' )[0], string.Join( ", " , self.GetGenericArguments().Select( c => c.GetGenericName() ) ) ); } }
var x = new List<int>(); var y = new Dictionary<int, string>(); print( x.GetType().GetGenericName() ); // List<Int32> print( y.GetType().GetGenericName() ); // Dictionary<Int32, String>