繁体   English   中英

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

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

如果我有以下代码:

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

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

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

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

暂无
暂无

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

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