反射
本文介绍了反射 - 从 System.Type 实例获取泛型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述如果我有以下代码:
MyType<int> anInstance = new MyType<int>();Type type = anInstance.GetType();如何找出anInstance"是哪个类型的参数?通过查看类型变量来实例化?可能吗?
How can I find out which type argument(s) "anInstance" was instantiated with, by looking at the type variable? Is it possible?
推荐答案使用 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反射