ジェネリック型の型パラメータ(例えばList<int>
における< >
内の部分)を取得したい場合はGetGenericArgumentsメソッドを使うことができます。 型パラメータの情報もTypeクラスとして取得されます。 Typeが型パラメータを表す場合、IsGenericParameterプロパティがtrueとなります。
GetGenericArgumentsメソッドは、オープンジェネリック型・クローズジェネリック型のどちらの型情報に対しても用いることができます。
ジェネリック型における型パラメータの型情報を取得する
using System;
using System.Collections.Generic;
class Sample {
static void Main()
{
ClassifyGenericType(typeof(List<>));
ClassifyGenericType(typeof(List<int>));
ClassifyGenericType(typeof(List<string>));
ClassifyGenericType(typeof(Dictionary<,>));
ClassifyGenericType(typeof(Dictionary<string, int>));
ClassifyGenericType(typeof(Action<,,,>));
ClassifyGenericType(typeof(Action<int, float, double, string>));
ClassifyGenericType(typeof(int));
}
static void ClassifyGenericType(Type t)
{
Console.Write("{0}: ", t.Name);
if (t.IsGenericType) {
// 型がジェネリック型の場合、ジェネリック型定義か構築ジェネリック型か調べる
if (t.IsGenericTypeDefinition)
Console.Write("ジェネリック型定義; ");
else
Console.Write("構築ジェネリック型; ");
// ジェネリック型の型パラメータの型情報を取得して表示する
foreach (var ta in t.GetGenericArguments()) {
Console.Write("{0}, ", ta.Name);
}
Console.WriteLine();
}
else {
Console.WriteLine("(非ジェネリック型)");
}
}
}
実行結果
List`1: ジェネリック型定義; T, List`1: 構築ジェネリック型; Int32, List`1: 構築ジェネリック型; String, Dictionary`2: ジェネリック型定義; TKey, TValue, Dictionary`2: 構築ジェネリック型; String, Int32, Action`4: ジェネリック型定義; T1, T2, T3, T4, Action`4: 構築ジェネリック型; Int32, Single, Double, String, Int32: (非ジェネリック型)
ジェネリックメソッドの型パラメータも同様に取得することができます。 この場合、まず対象となるジェネリックメソッドのMethodInfoを取得し、その後MethodInfo.GetGenericArgumentsメソッドを呼び出します。
この例で使用しているGetMethodメソッドについては後述の§.メンバ情報の取得 (MemberInfo)で解説しています。 また、型パラメータを含むメソッドやジェネリックメソッドの取得に関しては§.型パラメータを指定した取得 (ジェネリック型のメソッド/ジェネリックメソッドの取得)を参照してください。