Подтвердить что ты не робот

Отражение. Получение общих параметров из экземпляра System.Type.

Если у меня есть следующий код:

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

Как узнать, какой тип параметра "anInstance" был создан с помощью переменной типа? Является ли это возможным?

4b9b3361

Ответ 1

Используйте 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

Ответ 2

Используйте 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