反射 - 从System.Type实例中获取泛型参数

38
如果我有以下代码:

If I have the following code:

MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();

通过查看类型变量,我如何找出“anInstance”实例化时使用的哪些类型参数?这可能吗?

2个回答

62

使用 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

12
使用Type.GetGenericArguments()。例如:
using System;
using System.Reflection;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      MyType<int> anInstance = new MyType<int>();
      Type type = anInstance.GetType();
      foreach (Type t in type.GetGenericArguments())
        Console.WriteLine(t.Name);
      Console.ReadLine();
    }
  }
  public class MyType<T> { }
}

输出: Int32

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接