简体   繁体   English

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

[英]Reflection - Getting the generic arguments from a System.Type instance

If I have the following code:如果我有以下代码:

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

How can I find out which type argument(s) "anInstance" was instantiated with, by looking at the type variable?如何通过查看类型变量找出实例化了哪个类型参数“anInstance”? Is it possible?是否可以?

Use Type.GetGenericArguments .使用Type.GetGenericArguments For example:例如:

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);
        }
    }
}

Output:输出:

Type arguments:
  System.String
  System.Int32

Use Type.GetGenericArguments().使用 Type.GetGenericArguments()。 For example:例如:

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> { }
}

Output: Int32输出:Int32

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM