如果我有以下代码:
MyTypeanInstance = new MyType (); Type type = anInstance.GetType();
通过查看类型变量,如何找出实例化的"anInstance"类型参数?可能吗 ?
使用Type.GetGenericArguments.例如:
using System; using System.Collections.Generic; public class Test { static void Main() { var dict = new Dictionary(); Type type = dict.GetType(); Console.WriteLine("Type arguments:"); foreach (Type arg in type.GetGenericArguments()) { Console.WriteLine(" {0}", arg); } } }
输出:
Type arguments: System.String System.Int32
使用Type.GetGenericArguments().例如:
using System; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyTypeanInstance = new MyType (); Type type = anInstance.GetType(); foreach (Type t in type.GetGenericArguments()) Console.WriteLine(t.Name); Console.ReadLine(); } } public class MyType { } }
输出:Int32