如果我有以下代码:
MyType<int> anInstance = new MyType<int>(); Type type = anInstance.GetType();
如何通过查看类型变量来找出实例化了哪个类型参数“ anInstance”?可能吗 ?
使用Type.GetGenericArguments。例如:
using System; using System.Collections.Generic; public class Test { static void Main() { var dict = new Dictionary<string, int>(); Type type = dict.GetType(); Console.WriteLine("Type arguments:"); foreach (Type arg in type.GetGenericArguments()) { Console.WriteLine(" {0}", arg); } } }
输出:
Type arguments: System.String System.Int32