反思 - 从System.Type的实例获取泛型参数实例、参数、System、Type

2023-09-02 21:08:31 作者:此侽甚暖

如果我有以下的code:

If I have the following code:

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

我如何可以找出哪些类型参数(S)anInstance被实例化,通过查看类型变量?可能吗 ?

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

推荐答案

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