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

C# 反射-从System.Type实例获取泛型参数,c#,.net,reflection,generic-type-argument,C#,.net,Reflection,Generic Type Argument,如果我有以下代码: MyType<int> anInstance = new MyType<int>(); Type type = anInstance.GetType(); MyType anInstance=new MyType(); Type Type=anInstance.GetType(); 如何通过查看类型变量来找出实例化“anInstance”的类型参数?可能吗?使用。例如: using System; using System.Collections.

如果我有以下代码:

MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();
MyType anInstance=new MyType();
Type Type=anInstance.GetType();
如何通过查看类型变量来找出实例化“anInstance”的类型参数?可能吗?

使用。例如:

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

使用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);
        }
    }
}
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> { }
}
使用系统;
运用系统反思;
命名空间控制台应用程序1{
班级计划{
静态void Main(字符串[]参数){
MyType anInstance=新的MyType();
Type Type=anInstance.GetType();
foreach(Type.GetGenericArguments()中的类型t)
Console.WriteLine(t.Name);
Console.ReadLine();
}
}
公共类MyType{}
}
输出: Int32