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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/293905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:58:04  来源:igfitidea点击:

Reflection - Getting the generic parameters from a System.Type instance

c#.netreflectiongeneric-type-argument

提问by driis

If I have the following code:

如果我有以下代码:

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

How can I find out which type parameter(s) "anInstance" was instantiated with, by looking at the type variable ? Is it possible ?

如何通过查看类型变量找出实例化了哪个类型参数“anInstance”?是否可以 ?

采纳答案by Jon Skeet

Use Type.GetGenericArguments. For example:

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

Output:

输出:

Type arguments:
  System.String
  System.Int32

回答by Hans Passant

Use Type.GetGenericArguments(). For example:

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

Output: Int32

输出:Int32