反射 - 从 System.Type 实例获取泛型参数 [英] Reflection - Getting the generic arguments from a System.Type instance

查看:17
本文介绍了反射 - 从 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

这篇关于反射 - 从 System.Type 实例获取泛型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆